diff --git a/tasks/ohmyzsh__ohmyzsh-13922/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-13922/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..440bd5c76e225538cd4516b93970667933699412 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13922/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace bd77419b2ab106006f3982055cb92f029af92e49 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-13922/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-13922/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13922/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-13926/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-13926/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..540f2233ae9b0757620ffe77ed7ad9ac5cf8f045 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13926/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 99aaf58d007f1378d1e0609bcd9baf8abbbaf327 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 99aaf58d007f1378d1e0609bcd9baf8abbbaf327 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 99aaf58d007f1378d1e0609bcd9baf8abbbaf327 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-13926/instruction.md b/tasks/ohmyzsh__ohmyzsh-13926/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4337acaff4c14125b1ba1be96567b89495d8fc95 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13926/instruction.md @@ -0,0 +1,120 @@ +# Issue + +**Title:** chore(deps): bump the gha-minor group with 2 updates + +## Description + +Bumps the gha-minor group with 2 updates: [step-security/harden-runner](https://github.com/step-security/harden-runner) and [github/codeql-action/upload-sarif](https://github.com/github/codeql-action). + +Updates `step-security/harden-runner` from 2.20.0 to 2.20.1 +
+Release notes +

Sourced from step-security/harden-runner's releases.

+
+

v2.20.1

+

What's Changed

+
    +
  • AWS CodeBuild-hosted runner support
  • +
  • Implicitly allow single-labeled (internal) domains in block-mode
  • +
+

Full Changelog: https://github.com/step-security/harden-runner/compare/v2.20.0...v2.20.1

+
+
+
+Commits +
    +
  • b09bb98 Merge pull request #680 from step-security/aws-code-build
  • +
  • 35cd77b docs: document the Global Block List in the features list
  • +
  • bb6dbef chore: rebuild dist with clean dependency install
  • +
  • 98f73c5 chore: update eBPF agent to v1.8.14
  • +
  • 54193c1 Reapply "feat(runners): detect AWS CodeBuild-hosted runners as third-party pr...
  • +
  • d22dd48 Revert "fix(self-hosted): flush agent events at job end when deploy-on-self-h...
  • +
  • 0ff0941 fix(self-hosted): flush agent events at job end when deploy-on-self-hosted-vm...
  • +
  • a3c333d Revert "feat(runners): detect AWS CodeBuild-hosted runners as third-party pro...
  • +
  • bf94c00 feat(runners): detect AWS CodeBuild-hosted runners as third-party provider
  • +
  • 514522c fix(self-hosted): resolve runner user when USER env var is unset
  • +
  • See full diff in compare view
  • +
+
+
+ +Updates `github/codeql-action/upload-sarif` from 4.37.4 to 4.37.6 +
+Release notes +

Sourced from github/codeql-action/upload-sarif's releases.

+
+

v4.37.6

+
    +
  • Changed the default filepath for the new remote file address format that was introduced in CodeQL Action 4.37.0 / 3.37.0 to .github/codeql-config.yml to align it with the suggested path that is used elsewhere. #4070
  • +
+

v4.37.5

+
    +
  • Fixed a bug where a network error while streaming the download of the CodeQL bundle could terminate the init Action instead of falling back to downloading the bundle before extracting it. #4061
  • +
+
+
+
+Changelog +

Sourced from github/codeql-action/upload-sarif's changelog.

+
+

CodeQL Action Changelog

+

See the releases page for the relevant changes to the CodeQL CLI and language packs.

+

[UNRELEASED]

+

No user facing changes.

+

4.37.6 - 04 Aug 2026

+
    +
  • Changed the default filepath for the new remote file address format that was introduced in CodeQL Action 4.37.0 / 3.37.0 to .github/codeql-config.yml to align it with the suggested path that is used elsewhere. #4070
  • +
+

4.37.5 - 03 Aug 2026

+
    +
  • Fixed a bug where a network error while streaming the download of the CodeQL bundle could terminate the init Action instead of falling back to downloading the bundle before extracting it. #4061
  • +
+

4.37.4 - 29 Jul 2026

+
    +
  • This version of the CodeQL Action adds support for the tools input for the codeql-action/init step to be specified using a github-codeql-tools repository property. This feature will gradually be rolled out following the release of this version. Once rolled out, this allows for the CodeQL CLI version that is used in GitHub-managed workflows, such as Default Setup, to be set to a custom value. For example, customers who run into issues with rate limits when a new CodeQL CLI version is released can set the value to toolcache to always use the CodeQL CLI version that is available in the runner toolcache. For Advanced Setup workflows, the value provided for tools in the workflow definition always takes precedence unless the value of the repository property starts with !. #4037
  • +
  • Update default CodeQL bundle version to 2.26.2. #4051
  • +
+

4.37.3 - 22 Jul 2026

+

No user facing changes.

+

4.37.2 - 21 Jul 2026

+
    +
  • The new address format for the config-file input that was introduced in CodeQL Action 4.37.0 is now enabled by default. In addition to the format described there, the remote= prefix can now be used to explicitly indicate that the input refers to a remote file. All previous input formats continue to be accepted as well. #4023
  • +
  • The CodeQL Action can now make use of configured private registries in Default Setup to retrieve CodeQL configuration files from remote repositories that require authentication. This will allow customers to store their CodeQL configuration in a single repository that can then be referenced by Default Setup workflows in other repositories. We expect to roll this and other, related changes out to everyone in July. #4007
  • +
+

4.37.1 - 16 Jul 2026

+
    +
  • Upcoming breaking change: Add a deprecation warning for customers using CodeQL version 2.20.6 and earlier. These versions of CodeQL were discontinued on 1 July 2026 alongside GitHub Enterprise Server 3.16, and will be unsupported by the next minor release of the CodeQL Action. #3956
  • +
  • Update default CodeQL bundle version to 2.26.1. #4019
  • +
+

4.37.0 - 08 Jul 2026

+
    +
  • Update default CodeQL bundle version to 2.26.0. #3995
  • +
  • In addition to the existing input format, the config-file input for the codeql-action/init step will soon support a new [owner/]repo[@ref][:path] format. All components except the repository name are optional. If omitted, owner defaults to the same owner as the repository the analysis is running for, ref to main, and path to .github/codeql-action.yaml. Support for this format ships in this version of the CodeQL Action, but will only be enabled over the coming weeks. #3973
  • +
+

4.36.3 - 01 Jul 2026

+

No user facing changes.

+

4.36.2 - 04 Jun 2026

+
    +
  • Cache CodeQL CLI version information across Actions steps. #3943
  • +
  • Reduce requests while waiting for analysis processing by using exponential backoff when polling SARIF processing status. #3937
  • +
  • Update default CodeQL bundle version to 2.25.6. #3948
  • +
+ +
+

... (truncated)

+
+
+Commits +
    +
  • 5595cca Merge pull request #4071 from github/update-v4.37.6-6a9359a1b
  • +
  • ec9c757 Add change note for PR 4070
  • +
  • 45c8742 Update changelog for v4.37.6
  • +
  • 6a9359a Merge pull request #4070 from github/mbg/remote-address/change-file-default
  • +
  • 065cdc0 Change DEFAULT_CONFIG_FILE_NAME
  • +
  • f99dd5a Merge pull request #4066 from github/dependabot/npm_and_yarn/js-yaml-5.2.2
  • +
  • 1804b21 Merge pull request #4068 from github/mergeback/v4.37.5-to-main-d1ba80a1
  • +
  • 3020a + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `99aaf58d007f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13926/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-13926/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..38042823ccfd1c8238b5ae1fefa5d96dd1489230 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13926/solution/patch.diff @@ -0,0 +1,82 @@ +diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml +index ab527296..212cfbf0 100644 +--- a/.github/workflows/dependencies.yml ++++ b/.github/workflows/dependencies.yml +@@ -16,7 +16,7 @@ jobs: + contents: write # this is needed to push commits and branches + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 ++ uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 + with: + egress-policy: audit + +diff --git a/.github/workflows/installer.yml b/.github/workflows/installer.yml +index 916cb781..04acc67a 100644 +--- a/.github/workflows/installer.yml ++++ b/.github/workflows/installer.yml +@@ -26,7 +26,7 @@ jobs: + - macos-latest + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 ++ uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 + with: + egress-policy: audit + +@@ -47,7 +47,7 @@ jobs: + - test + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 ++ uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 + with: + egress-policy: audit + +diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml +index 93a25d6d..8b83613d 100644 +--- a/.github/workflows/main.yml ++++ b/.github/workflows/main.yml +@@ -24,7 +24,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 ++ uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 + with: + egress-policy: audit + +diff --git a/.github/workflows/project.yml b/.github/workflows/project.yml +index b9489cf6..f6daabdb 100644 +--- a/.github/workflows/project.yml ++++ b/.github/workflows/project.yml +@@ -17,7 +17,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 ++ uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 + with: + egress-policy: audit + - name: Authenticate as @ohmyzsh +diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml +index c2d50610..ca577b9a 100644 +--- a/.github/workflows/scorecard.yml ++++ b/.github/workflows/scorecard.yml +@@ -36,7 +36,7 @@ jobs: + + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 ++ uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 + with: + egress-policy: audit + +@@ -60,6 +60,6 @@ jobs: + retention-days: 5 + + - name: "Upload to code-scanning" +- uses: github/codeql-action/upload-sarif@f205ea1c3313d32999d8d6a48b4f6530d4437b38 # v4.37.4 ++ uses: github/codeql-action/upload-sarif@5595ccaf912efad79be6eef63a5619ff05969be3 # v4.37.6 + with: + sarif_file: results.sarif diff --git a/tasks/ohmyzsh__ohmyzsh-13926/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-13926/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13926/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-13926/task.toml b/tasks/ohmyzsh__ohmyzsh-13926/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..882b181672f0d646ca1a014fbef939470b6aa543 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13926/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-13926" +description = "chore(deps): bump the gha-minor group with 2 updates" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "99aaf58d007f1378d1e0609bcd9baf8abbbaf327" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/13926" +source_access = "auto" +built_at = "2026-11-16T16:09:57.037579+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:db28f6c5f5b6e709b2646e56308f84f0c5db196ba9a341894ffbdc2aa9312a97" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-09T13:17:49Z" +diff_format = "unified" +context_files = [ + ".github/workflows/dependencies.yml", + ".github/workflows/installer.yml", + ".github/workflows/main.yml", + ".github/workflows/project.yml", + ".github/workflows/scorecard.yml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 14 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.957759+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c5ed282de93c2db49882ad4d688fa75d63708265d048196b2975a7baa3eff119" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-13926/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-13926/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13926/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-13926/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-13926/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4337acaff4c14125b1ba1be96567b89495d8fc95 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13926/tests/instruction.md @@ -0,0 +1,120 @@ +# Issue + +**Title:** chore(deps): bump the gha-minor group with 2 updates + +## Description + +Bumps the gha-minor group with 2 updates: [step-security/harden-runner](https://github.com/step-security/harden-runner) and [github/codeql-action/upload-sarif](https://github.com/github/codeql-action). + +Updates `step-security/harden-runner` from 2.20.0 to 2.20.1 +
    +Release notes +

    Sourced from step-security/harden-runner's releases.

    +
    +

    v2.20.1

    +

    What's Changed

    +
      +
    • AWS CodeBuild-hosted runner support
    • +
    • Implicitly allow single-labeled (internal) domains in block-mode
    • +
    +

    Full Changelog: https://github.com/step-security/harden-runner/compare/v2.20.0...v2.20.1

    +
    +
    +
    +Commits +
      +
    • b09bb98 Merge pull request #680 from step-security/aws-code-build
    • +
    • 35cd77b docs: document the Global Block List in the features list
    • +
    • bb6dbef chore: rebuild dist with clean dependency install
    • +
    • 98f73c5 chore: update eBPF agent to v1.8.14
    • +
    • 54193c1 Reapply "feat(runners): detect AWS CodeBuild-hosted runners as third-party pr...
    • +
    • d22dd48 Revert "fix(self-hosted): flush agent events at job end when deploy-on-self-h...
    • +
    • 0ff0941 fix(self-hosted): flush agent events at job end when deploy-on-self-hosted-vm...
    • +
    • a3c333d Revert "feat(runners): detect AWS CodeBuild-hosted runners as third-party pro...
    • +
    • bf94c00 feat(runners): detect AWS CodeBuild-hosted runners as third-party provider
    • +
    • 514522c fix(self-hosted): resolve runner user when USER env var is unset
    • +
    • See full diff in compare view
    • +
    +
    +
    + +Updates `github/codeql-action/upload-sarif` from 4.37.4 to 4.37.6 +
    +Release notes +

    Sourced from github/codeql-action/upload-sarif's releases.

    +
    +

    v4.37.6

    +
      +
    • Changed the default filepath for the new remote file address format that was introduced in CodeQL Action 4.37.0 / 3.37.0 to .github/codeql-config.yml to align it with the suggested path that is used elsewhere. #4070
    • +
    +

    v4.37.5

    +
      +
    • Fixed a bug where a network error while streaming the download of the CodeQL bundle could terminate the init Action instead of falling back to downloading the bundle before extracting it. #4061
    • +
    +
    +
    +
    +Changelog +

    Sourced from github/codeql-action/upload-sarif's changelog.

    +
    +

    CodeQL Action Changelog

    +

    See the releases page for the relevant changes to the CodeQL CLI and language packs.

    +

    [UNRELEASED]

    +

    No user facing changes.

    +

    4.37.6 - 04 Aug 2026

    +
      +
    • Changed the default filepath for the new remote file address format that was introduced in CodeQL Action 4.37.0 / 3.37.0 to .github/codeql-config.yml to align it with the suggested path that is used elsewhere. #4070
    • +
    +

    4.37.5 - 03 Aug 2026

    +
      +
    • Fixed a bug where a network error while streaming the download of the CodeQL bundle could terminate the init Action instead of falling back to downloading the bundle before extracting it. #4061
    • +
    +

    4.37.4 - 29 Jul 2026

    +
      +
    • This version of the CodeQL Action adds support for the tools input for the codeql-action/init step to be specified using a github-codeql-tools repository property. This feature will gradually be rolled out following the release of this version. Once rolled out, this allows for the CodeQL CLI version that is used in GitHub-managed workflows, such as Default Setup, to be set to a custom value. For example, customers who run into issues with rate limits when a new CodeQL CLI version is released can set the value to toolcache to always use the CodeQL CLI version that is available in the runner toolcache. For Advanced Setup workflows, the value provided for tools in the workflow definition always takes precedence unless the value of the repository property starts with !. #4037
    • +
    • Update default CodeQL bundle version to 2.26.2. #4051
    • +
    +

    4.37.3 - 22 Jul 2026

    +

    No user facing changes.

    +

    4.37.2 - 21 Jul 2026

    +
      +
    • The new address format for the config-file input that was introduced in CodeQL Action 4.37.0 is now enabled by default. In addition to the format described there, the remote= prefix can now be used to explicitly indicate that the input refers to a remote file. All previous input formats continue to be accepted as well. #4023
    • +
    • The CodeQL Action can now make use of configured private registries in Default Setup to retrieve CodeQL configuration files from remote repositories that require authentication. This will allow customers to store their CodeQL configuration in a single repository that can then be referenced by Default Setup workflows in other repositories. We expect to roll this and other, related changes out to everyone in July. #4007
    • +
    +

    4.37.1 - 16 Jul 2026

    +
      +
    • Upcoming breaking change: Add a deprecation warning for customers using CodeQL version 2.20.6 and earlier. These versions of CodeQL were discontinued on 1 July 2026 alongside GitHub Enterprise Server 3.16, and will be unsupported by the next minor release of the CodeQL Action. #3956
    • +
    • Update default CodeQL bundle version to 2.26.1. #4019
    • +
    +

    4.37.0 - 08 Jul 2026

    +
      +
    • Update default CodeQL bundle version to 2.26.0. #3995
    • +
    • In addition to the existing input format, the config-file input for the codeql-action/init step will soon support a new [owner/]repo[@ref][:path] format. All components except the repository name are optional. If omitted, owner defaults to the same owner as the repository the analysis is running for, ref to main, and path to .github/codeql-action.yaml. Support for this format ships in this version of the CodeQL Action, but will only be enabled over the coming weeks. #3973
    • +
    +

    4.36.3 - 01 Jul 2026

    +

    No user facing changes.

    +

    4.36.2 - 04 Jun 2026

    +
      +
    • Cache CodeQL CLI version information across Actions steps. #3943
    • +
    • Reduce requests while waiting for analysis processing by using exponential backoff when polling SARIF processing status. #3937
    • +
    • Update default CodeQL bundle version to 2.25.6. #3948
    • +
    + +
    +

    ... (truncated)

    +
    +
    +Commits +
      +
    • 5595cca Merge pull request #4071 from github/update-v4.37.6-6a9359a1b
    • +
    • ec9c757 Add change note for PR 4070
    • +
    • 45c8742 Update changelog for v4.37.6
    • +
    • 6a9359a Merge pull request #4070 from github/mbg/remote-address/change-file-default
    • +
    • 065cdc0 Change DEFAULT_CONFIG_FILE_NAME
    • +
    • f99dd5a Merge pull request #4066 from github/dependabot/npm_and_yarn/js-yaml-5.2.2
    • +
    • 1804b21 Merge pull request #4068 from github/mergeback/v4.37.5-to-main-d1ba80a1
    • +
    • 3020a + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `99aaf58d007f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13926/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-13926/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..38042823ccfd1c8238b5ae1fefa5d96dd1489230 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13926/tests/oracle.patch @@ -0,0 +1,82 @@ +diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml +index ab527296..212cfbf0 100644 +--- a/.github/workflows/dependencies.yml ++++ b/.github/workflows/dependencies.yml +@@ -16,7 +16,7 @@ jobs: + contents: write # this is needed to push commits and branches + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 ++ uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 + with: + egress-policy: audit + +diff --git a/.github/workflows/installer.yml b/.github/workflows/installer.yml +index 916cb781..04acc67a 100644 +--- a/.github/workflows/installer.yml ++++ b/.github/workflows/installer.yml +@@ -26,7 +26,7 @@ jobs: + - macos-latest + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 ++ uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 + with: + egress-policy: audit + +@@ -47,7 +47,7 @@ jobs: + - test + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 ++ uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 + with: + egress-policy: audit + +diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml +index 93a25d6d..8b83613d 100644 +--- a/.github/workflows/main.yml ++++ b/.github/workflows/main.yml +@@ -24,7 +24,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 ++ uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 + with: + egress-policy: audit + +diff --git a/.github/workflows/project.yml b/.github/workflows/project.yml +index b9489cf6..f6daabdb 100644 +--- a/.github/workflows/project.yml ++++ b/.github/workflows/project.yml +@@ -17,7 +17,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 ++ uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 + with: + egress-policy: audit + - name: Authenticate as @ohmyzsh +diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml +index c2d50610..ca577b9a 100644 +--- a/.github/workflows/scorecard.yml ++++ b/.github/workflows/scorecard.yml +@@ -36,7 +36,7 @@ jobs: + + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0 ++ uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 + with: + egress-policy: audit + +@@ -60,6 +60,6 @@ jobs: + retention-days: 5 + + - name: "Upload to code-scanning" +- uses: github/codeql-action/upload-sarif@f205ea1c3313d32999d8d6a48b4f6530d4437b38 # v4.37.4 ++ uses: github/codeql-action/upload-sarif@5595ccaf912efad79be6eef63a5619ff05969be3 # v4.37.6 + with: + sarif_file: results.sarif diff --git a/tasks/ohmyzsh__ohmyzsh-13926/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-13926/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..bcf1428fa41f4f186b0038991bf538d653119bfa --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13926/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 99aaf58d007f1378d1e0609bcd9baf8abbbaf327 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-13926/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-13926/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13926/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-13930/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-13930/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c783abd527b890266a4e3d6f1802e1bd4d85a52e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13930/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 97b27bb2ec0701330b18c2d3e340b22e742b3fa8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 97b27bb2ec0701330b18c2d3e340b22e742b3fa8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 97b27bb2ec0701330b18c2d3e340b22e742b3fa8 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-13930/instruction.md b/tasks/ohmyzsh__ohmyzsh-13930/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e40558162ca2521bb29bef182b82328de8ce363b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13930/instruction.md @@ -0,0 +1,59 @@ +# Issue + +**Title:** feat(sublime-merge): Add an smerge alias + +## Description + +The available command that ships with Sublime Text is `subl`, but with Sublime Merge, it's `smerge`. However, at least on macOS, neither application adds those executables to the `PATH`. + +The Sublime Text plugin searches a few potential directories for the `subl` executable and [creates an alias that points to it](https://github.com/ohmyzsh/ohmyzsh/blob/97b27bb2ec0701330b18c2d3e340b22e742b3fa8/plugins/sublime/sublime.plugin.zsh#L64): +```zsh + for _sublime_path in $_sublime_paths; do + if [[ -a $_sublime_path ]]; then + alias subl="'$_sublime_path'" + (( $+commands[sudo] )) && alias sst="sudo -EH '$_sublime_path'" + break + fi + done +``` + +And while the plugin for Sublime Merge did a good job creating a corresponding `subm` alias, it didn't create an alias for the `smerge` executable, it creates a `subm` alias isntead: + +```zsh + for _sublime_merge_path in $_sublime_darwin_paths; do + if [[ -a $_sublime_merge_path ]]; then + subm () { "$_sublime_merge_path" "$@" } + alias sm=subm + break + fi + done +``` + +This PR fixes that by also creating an `smerge` alias that points to the `smerge` executable that ships with Sublime Merge. +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- [x] Add an `smerge` alias for the `smerge` executable that is distributed with Sublime Merge. + +## Other comments: + +I realize that one more alias isn't hugely necessary, but removes the need for Sublime Merge users to find and alias `smerge` from the Sublime Merge installation, or to add the Sublime Merge installation to their `PATH`. And making applications easier to use from the command line is, after all, the entire point of plugins. + +Tested on macOS only, but the changes are pretty minimal and I each added line is the same (I literally copied and pasted). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `97b27bb2ec07`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13930/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-13930/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2e9acea44cddaf7c2c69e87632e930997068abbc --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13930/solution/patch.diff @@ -0,0 +1,28 @@ +diff --git a/plugins/sublime-merge/sublime-merge.plugin.zsh b/plugins/sublime-merge/sublime-merge.plugin.zsh +index 15452e61..26bbe1fa 100644 +--- a/plugins/sublime-merge/sublime-merge.plugin.zsh ++++ b/plugins/sublime-merge/sublime-merge.plugin.zsh +@@ -19,6 +19,7 @@ + ssm_run_sudo() {sudo $_sublime_merge_path "$@" >/dev/null 2>&1} + alias ssm=ssm_run_sudo + alias sm=sm_run ++ alias smerge="'$_sublime_merge_path'" + break + fi + done +@@ -33,6 +34,7 @@ + if [[ -a $_sublime_merge_path ]]; then + subm () { "$_sublime_merge_path" "$@" } + alias sm=subm ++ alias smerge="'$_sublime_merge_path'" + break + fi + done +@@ -45,6 +47,7 @@ + if [[ -a $_sublime_merge_path ]]; then + subm () { "$_sublime_merge_path" "$@" } + alias sm=subm ++ alias smerge="'$_sublime_merge_path'" + break + fi + done diff --git a/tasks/ohmyzsh__ohmyzsh-13930/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-13930/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13930/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-13930/task.toml b/tasks/ohmyzsh__ohmyzsh-13930/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e955600f22e76faa49c13d6b7b00c35a60211fdb --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13930/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-13930" +description = "feat(sublime-merge): Add an smerge alias" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "97b27bb2ec0701330b18c2d3e340b22e742b3fa8" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/13930" +source_access = "auto" +built_at = "2026-11-16T16:09:57.008323+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:203ecde185d49b0388b50a9baf8bc1c6bd6bfd51421b4505e1fc36c54bd6ce14" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-04T21:49:55Z" +diff_format = "unified" +context_files = [ + "plugins/sublime-merge/sublime-merge.plugin.zsh", +] +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.958290+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:286154074d0269adef526a2ddf966944e2286fec1e2f81a2f980bb6c737f8c0d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-13930/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-13930/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13930/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-13930/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-13930/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e40558162ca2521bb29bef182b82328de8ce363b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13930/tests/instruction.md @@ -0,0 +1,59 @@ +# Issue + +**Title:** feat(sublime-merge): Add an smerge alias + +## Description + +The available command that ships with Sublime Text is `subl`, but with Sublime Merge, it's `smerge`. However, at least on macOS, neither application adds those executables to the `PATH`. + +The Sublime Text plugin searches a few potential directories for the `subl` executable and [creates an alias that points to it](https://github.com/ohmyzsh/ohmyzsh/blob/97b27bb2ec0701330b18c2d3e340b22e742b3fa8/plugins/sublime/sublime.plugin.zsh#L64): +```zsh + for _sublime_path in $_sublime_paths; do + if [[ -a $_sublime_path ]]; then + alias subl="'$_sublime_path'" + (( $+commands[sudo] )) && alias sst="sudo -EH '$_sublime_path'" + break + fi + done +``` + +And while the plugin for Sublime Merge did a good job creating a corresponding `subm` alias, it didn't create an alias for the `smerge` executable, it creates a `subm` alias isntead: + +```zsh + for _sublime_merge_path in $_sublime_darwin_paths; do + if [[ -a $_sublime_merge_path ]]; then + subm () { "$_sublime_merge_path" "$@" } + alias sm=subm + break + fi + done +``` + +This PR fixes that by also creating an `smerge` alias that points to the `smerge` executable that ships with Sublime Merge. +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- [x] Add an `smerge` alias for the `smerge` executable that is distributed with Sublime Merge. + +## Other comments: + +I realize that one more alias isn't hugely necessary, but removes the need for Sublime Merge users to find and alias `smerge` from the Sublime Merge installation, or to add the Sublime Merge installation to their `PATH`. And making applications easier to use from the command line is, after all, the entire point of plugins. + +Tested on macOS only, but the changes are pretty minimal and I each added line is the same (I literally copied and pasted). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `97b27bb2ec07`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13930/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-13930/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2e9acea44cddaf7c2c69e87632e930997068abbc --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13930/tests/oracle.patch @@ -0,0 +1,28 @@ +diff --git a/plugins/sublime-merge/sublime-merge.plugin.zsh b/plugins/sublime-merge/sublime-merge.plugin.zsh +index 15452e61..26bbe1fa 100644 +--- a/plugins/sublime-merge/sublime-merge.plugin.zsh ++++ b/plugins/sublime-merge/sublime-merge.plugin.zsh +@@ -19,6 +19,7 @@ + ssm_run_sudo() {sudo $_sublime_merge_path "$@" >/dev/null 2>&1} + alias ssm=ssm_run_sudo + alias sm=sm_run ++ alias smerge="'$_sublime_merge_path'" + break + fi + done +@@ -33,6 +34,7 @@ + if [[ -a $_sublime_merge_path ]]; then + subm () { "$_sublime_merge_path" "$@" } + alias sm=subm ++ alias smerge="'$_sublime_merge_path'" + break + fi + done +@@ -45,6 +47,7 @@ + if [[ -a $_sublime_merge_path ]]; then + subm () { "$_sublime_merge_path" "$@" } + alias sm=subm ++ alias smerge="'$_sublime_merge_path'" + break + fi + done diff --git a/tasks/ohmyzsh__ohmyzsh-13930/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-13930/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..05ffe21b96f89233d2d2d0a7952bd5bd087d51af --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13930/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 97b27bb2ec0701330b18c2d3e340b22e742b3fa8 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-13930/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-13930/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13930/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-13932/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-13932/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5ab936088be9150cf324c8f13f0dde7758d61cfe --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13932/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b54a71977574cfcf659cc2f15a5e6422f17a8da7 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b54a71977574cfcf659cc2f15a5e6422f17a8da7 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b54a71977574cfcf659cc2f15a5e6422f17a8da7 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-13932/instruction.md b/tasks/ohmyzsh__ohmyzsh-13932/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ff3cdd555dd42aa399d2f8d1252e686a72233a98 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13932/instruction.md @@ -0,0 +1,44 @@ +# Issue + +**Title:** fix(poetry-env): preserve venv in project subdirectories + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Keep the active Poetry environment while navigating ordinary project subdirectories. +- Deactivate and switch when entering a valid nested Poetry project. +- Match project paths on a directory boundary, so a sibling such as `project2` is not treated as a child of `project`. +- Document the two marker files and the navigation behavior. + +. + +## Testing: + +- Ran the repository's CI syntax command locally: all 579 matched Zsh files passed `zsh -n`. +- Ran an isolated `zsh -f` navigation smoke test covering project activation, ordinary and incomplete nested directories, a valid nested Poetry project, its child, returning to the parent project, a same-prefix sibling project, paths with spaces, and leaving the project tree. +- Reproduced the original child-directory deactivation against `origin/master`; all eight navigation scenarios pass with this branch. + +## Other comments: + +No aliases are introduced, so the alias-use-case checklist item is not applicable. + +AI-assisted: Codex analyzed the existing state transitions, drafted the condition, and assembled the test matrix. The final condition was cross-checked against the reported regression and edge cases, and the tests above were run locally. + +cc @carlosala + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b54a71977574`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13932/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-13932/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a4962485036295a7541e5b394da1a001a369cf37 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13932/solution/patch.diff @@ -0,0 +1,50 @@ +diff --git a/plugins/poetry-env/README.md b/plugins/poetry-env/README.md +index bd99d2a9..03c50809 100644 +--- a/plugins/poetry-env/README.md ++++ b/plugins/poetry-env/README.md +@@ -1,7 +1,9 @@ + # Poetry Environment Plugin + +-This plugin automatically changes poetry environment when you cd into or out of the project directory. +-Note: Script looks for pyproject.toml file to determine poetry if its a poetry environment ++This plugin automatically activates a Poetry environment when you enter a ++directory containing both `pyproject.toml` and `poetry.lock`. It keeps the ++environment active in project subdirectories, switches to nested Poetry ++projects, and deactivates it when you leave the project tree. + + To use it, add `poetry-env` to the plugins array in your zshrc file: + +diff --git a/plugins/poetry-env/poetry-env.plugin.zsh b/plugins/poetry-env/poetry-env.plugin.zsh +index 5f6fd451..5949a048 100644 +--- a/plugins/poetry-env/poetry-env.plugin.zsh ++++ b/plugins/poetry-env/poetry-env.plugin.zsh +@@ -1,15 +1,24 @@ + _togglePoetryShell() { + # Determine if currently in a Poetry-managed directory + local in_poetry_dir=0 ++ local in_active_poetry_dir=0 + if [[ -f "$PWD/pyproject.toml" && -f "$PWD/poetry.lock" ]]; then + in_poetry_dir=1 + fi + +- # Deactivate the current environment if moving out of a Poetry directory or into a different Poetry directory +- if [[ $poetry_active -eq 1 ]] && { [[ $in_poetry_dir -eq 0 ]] || [[ "$PWD" != "$poetry_dir"* ]]; }; then +- export poetry_active=0 +- unset poetry_dir +- (( $+functions[deactivate] )) && deactivate ++ # Deactivate when leaving the active project or entering a nested project ++ if [[ $poetry_active -eq 1 ]]; then ++ local project_dir="${poetry_dir%/}" ++ if [[ "$PWD" == "$project_dir" || "$PWD" == "$project_dir"/* ]]; then ++ in_active_poetry_dir=1 ++ fi ++ ++ if [[ $in_active_poetry_dir -eq 0 ]] || ++ { [[ $in_poetry_dir -eq 1 ]] && [[ "$PWD" != "$poetry_dir" ]]; }; then ++ export poetry_active=0 ++ unset poetry_dir ++ (( $+functions[deactivate] )) && deactivate ++ fi + fi + + # Activate the environment if in a Poetry directory and no environment is currently active diff --git a/tasks/ohmyzsh__ohmyzsh-13932/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-13932/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13932/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-13932/task.toml b/tasks/ohmyzsh__ohmyzsh-13932/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0ef00a3dd84ef70737881f1c6e3959fcc9426192 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13932/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-13932" +description = "fix(poetry-env): preserve venv in project subdirectories" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "b54a71977574cfcf659cc2f15a5e6422f17a8da7" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/13932" +source_access = "auto" +built_at = "2026-11-16T16:09:57.001232+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:534e3b543e01f28726ed77176bf17faa774b816201ce7c8e81275531dbfad7a4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-05T19:41:41Z" +diff_format = "unified" +context_files = [ + "plugins/poetry-env/README.md", + "plugins/poetry-env/poetry-env.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 25 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.958900+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:48c104d5c7ac1aa7732448d20b936b78e49d8b4fcac90871610c967eecb978fc" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-13932/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-13932/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13932/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-13932/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-13932/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ff3cdd555dd42aa399d2f8d1252e686a72233a98 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13932/tests/instruction.md @@ -0,0 +1,44 @@ +# Issue + +**Title:** fix(poetry-env): preserve venv in project subdirectories + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Keep the active Poetry environment while navigating ordinary project subdirectories. +- Deactivate and switch when entering a valid nested Poetry project. +- Match project paths on a directory boundary, so a sibling such as `project2` is not treated as a child of `project`. +- Document the two marker files and the navigation behavior. + +. + +## Testing: + +- Ran the repository's CI syntax command locally: all 579 matched Zsh files passed `zsh -n`. +- Ran an isolated `zsh -f` navigation smoke test covering project activation, ordinary and incomplete nested directories, a valid nested Poetry project, its child, returning to the parent project, a same-prefix sibling project, paths with spaces, and leaving the project tree. +- Reproduced the original child-directory deactivation against `origin/master`; all eight navigation scenarios pass with this branch. + +## Other comments: + +No aliases are introduced, so the alias-use-case checklist item is not applicable. + +AI-assisted: Codex analyzed the existing state transitions, drafted the condition, and assembled the test matrix. The final condition was cross-checked against the reported regression and edge cases, and the tests above were run locally. + +cc @carlosala + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b54a71977574`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13932/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-13932/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a4962485036295a7541e5b394da1a001a369cf37 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13932/tests/oracle.patch @@ -0,0 +1,50 @@ +diff --git a/plugins/poetry-env/README.md b/plugins/poetry-env/README.md +index bd99d2a9..03c50809 100644 +--- a/plugins/poetry-env/README.md ++++ b/plugins/poetry-env/README.md +@@ -1,7 +1,9 @@ + # Poetry Environment Plugin + +-This plugin automatically changes poetry environment when you cd into or out of the project directory. +-Note: Script looks for pyproject.toml file to determine poetry if its a poetry environment ++This plugin automatically activates a Poetry environment when you enter a ++directory containing both `pyproject.toml` and `poetry.lock`. It keeps the ++environment active in project subdirectories, switches to nested Poetry ++projects, and deactivates it when you leave the project tree. + + To use it, add `poetry-env` to the plugins array in your zshrc file: + +diff --git a/plugins/poetry-env/poetry-env.plugin.zsh b/plugins/poetry-env/poetry-env.plugin.zsh +index 5f6fd451..5949a048 100644 +--- a/plugins/poetry-env/poetry-env.plugin.zsh ++++ b/plugins/poetry-env/poetry-env.plugin.zsh +@@ -1,15 +1,24 @@ + _togglePoetryShell() { + # Determine if currently in a Poetry-managed directory + local in_poetry_dir=0 ++ local in_active_poetry_dir=0 + if [[ -f "$PWD/pyproject.toml" && -f "$PWD/poetry.lock" ]]; then + in_poetry_dir=1 + fi + +- # Deactivate the current environment if moving out of a Poetry directory or into a different Poetry directory +- if [[ $poetry_active -eq 1 ]] && { [[ $in_poetry_dir -eq 0 ]] || [[ "$PWD" != "$poetry_dir"* ]]; }; then +- export poetry_active=0 +- unset poetry_dir +- (( $+functions[deactivate] )) && deactivate ++ # Deactivate when leaving the active project or entering a nested project ++ if [[ $poetry_active -eq 1 ]]; then ++ local project_dir="${poetry_dir%/}" ++ if [[ "$PWD" == "$project_dir" || "$PWD" == "$project_dir"/* ]]; then ++ in_active_poetry_dir=1 ++ fi ++ ++ if [[ $in_active_poetry_dir -eq 0 ]] || ++ { [[ $in_poetry_dir -eq 1 ]] && [[ "$PWD" != "$poetry_dir" ]]; }; then ++ export poetry_active=0 ++ unset poetry_dir ++ (( $+functions[deactivate] )) && deactivate ++ fi + fi + + # Activate the environment if in a Poetry directory and no environment is currently active diff --git a/tasks/ohmyzsh__ohmyzsh-13932/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-13932/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8490ebacda3bba810908ae3e3aa9430afaaa94eb --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13932/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b54a71977574cfcf659cc2f15a5e6422f17a8da7 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-13932/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-13932/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13932/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-13950/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-13950/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5ab936088be9150cf324c8f13f0dde7758d61cfe --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13950/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b54a71977574cfcf659cc2f15a5e6422f17a8da7 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b54a71977574cfcf659cc2f15a5e6422f17a8da7 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b54a71977574cfcf659cc2f15a5e6422f17a8da7 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-13950/instruction.md b/tasks/ohmyzsh__ohmyzsh-13950/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..870b0fe0e929ddff9683b374da0d1fce0e66c55f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13950/instruction.md @@ -0,0 +1,40 @@ +# Issue + +**Title:** feat(gcx): add completion plugin + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] The code does not introduce new aliases. + +## Changes: + +- Add Zsh completions for [gcx](https://github.com/grafana/gcx), Grafana's CLI for managing Grafana resources and Cloud product APIs. +- Generate completions with `gcx completion zsh` and cache them in `$ZSH_CACHE_DIR`. +- Add activation and cache documentation. + +## Testing: + +- Enabled the plugin locally with `plugins=(... gcx)`. +- Verified `gcx` command, subcommand, and flag completion interactively. +- Ran `zsh -n plugins/gcx/gcx.plugin.zsh`. +- Confirmed the plugin creates a non-empty `$ZSH_CACHE_DIR/completions/_gcx` cache file. + +## Other comments: + +AI-assisted: initial implementation generated with an AI coding assistant, then reviewed and tested manually. + +This is a new plugin. Additional `gcx` users are invited to test it and leave a `+1`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b54a71977574`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13950/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-13950/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..219b5e99266ef7af71edff252ded49e2f80ac6b3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13950/solution/patch.diff @@ -0,0 +1,48 @@ +diff --git a/plugins/gcx/README.md b/plugins/gcx/README.md +new file mode 100644 +index 00000000..3dc02bb3 +--- /dev/null ++++ b/plugins/gcx/README.md +@@ -0,0 +1,18 @@ ++# Grafana CLI plugin ++ ++This plugin adds completion for the [Grafana CLI (gcx)](https://github.com/grafana/gcx). ++ ++To use it, add `gcx` to the plugins array in your zshrc file: ++ ++```zsh ++plugins=(... gcx) ++``` ++ ++This plugin does not add any aliases. ++ ++## Cache ++ ++This plugin caches the completion script and automatically updates it when the ++plugin is loaded, which is usually when you start a new terminal emulator. ++ ++The cache is stored at `$ZSH_CACHE_DIR/completions/_gcx`. +diff --git a/plugins/gcx/gcx.plugin.zsh b/plugins/gcx/gcx.plugin.zsh +new file mode 100644 +index 00000000..278c1669 +--- /dev/null ++++ b/plugins/gcx/gcx.plugin.zsh +@@ -0,0 +1,18 @@ ++# Autocompletion for the Grafana CLI (gcx). ++if (( ! $+commands[gcx] )); then ++ return ++fi ++ ++# If the completion file doesn't exist yet, we need to autoload it and ++# bind it to `gcx`. Otherwise, compinit will have already done that. ++if [[ ! -f "$ZSH_CACHE_DIR/completions/_gcx" ]]; then ++ typeset -g -A _comps ++ autoload -Uz _gcx ++ _comps[gcx]=_gcx ++fi ++ ++zmodload -F zsh/files b:zf_mv ++() { ++ local TMPPREFIX="$ZSH_CACHE_DIR/completions/_gcx" ++ zf_mv -f -- =( gcx completion zsh ) "$TMPPREFIX" ++} &| diff --git a/tasks/ohmyzsh__ohmyzsh-13950/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-13950/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13950/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-13950/task.toml b/tasks/ohmyzsh__ohmyzsh-13950/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7735679f35b8cba6dc98537ad0a4cce374fd530b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13950/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-13950" +description = "feat(gcx): add completion plugin" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "b54a71977574cfcf659cc2f15a5e6422f17a8da7" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/13950" +source_access = "auto" +built_at = "2026-11-16T16:09:57.005377+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6a607df2af86e7861e40ced00759e9dfe5663d9b11c10db5f497af0d19f38dd5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-05T18:19:46Z" +diff_format = "unified" +context_files = [ + "plugins/gcx/README.md", + "plugins/gcx/gcx.plugin.zsh", +] +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.959427+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:48c104d5c7ac1aa7732448d20b936b78e49d8b4fcac90871610c967eecb978fc" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-13950/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-13950/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13950/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-13950/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-13950/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..870b0fe0e929ddff9683b374da0d1fce0e66c55f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13950/tests/instruction.md @@ -0,0 +1,40 @@ +# Issue + +**Title:** feat(gcx): add completion plugin + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] The code does not introduce new aliases. + +## Changes: + +- Add Zsh completions for [gcx](https://github.com/grafana/gcx), Grafana's CLI for managing Grafana resources and Cloud product APIs. +- Generate completions with `gcx completion zsh` and cache them in `$ZSH_CACHE_DIR`. +- Add activation and cache documentation. + +## Testing: + +- Enabled the plugin locally with `plugins=(... gcx)`. +- Verified `gcx` command, subcommand, and flag completion interactively. +- Ran `zsh -n plugins/gcx/gcx.plugin.zsh`. +- Confirmed the plugin creates a non-empty `$ZSH_CACHE_DIR/completions/_gcx` cache file. + +## Other comments: + +AI-assisted: initial implementation generated with an AI coding assistant, then reviewed and tested manually. + +This is a new plugin. Additional `gcx` users are invited to test it and leave a `+1`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b54a71977574`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13950/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-13950/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..219b5e99266ef7af71edff252ded49e2f80ac6b3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13950/tests/oracle.patch @@ -0,0 +1,48 @@ +diff --git a/plugins/gcx/README.md b/plugins/gcx/README.md +new file mode 100644 +index 00000000..3dc02bb3 +--- /dev/null ++++ b/plugins/gcx/README.md +@@ -0,0 +1,18 @@ ++# Grafana CLI plugin ++ ++This plugin adds completion for the [Grafana CLI (gcx)](https://github.com/grafana/gcx). ++ ++To use it, add `gcx` to the plugins array in your zshrc file: ++ ++```zsh ++plugins=(... gcx) ++``` ++ ++This plugin does not add any aliases. ++ ++## Cache ++ ++This plugin caches the completion script and automatically updates it when the ++plugin is loaded, which is usually when you start a new terminal emulator. ++ ++The cache is stored at `$ZSH_CACHE_DIR/completions/_gcx`. +diff --git a/plugins/gcx/gcx.plugin.zsh b/plugins/gcx/gcx.plugin.zsh +new file mode 100644 +index 00000000..278c1669 +--- /dev/null ++++ b/plugins/gcx/gcx.plugin.zsh +@@ -0,0 +1,18 @@ ++# Autocompletion for the Grafana CLI (gcx). ++if (( ! $+commands[gcx] )); then ++ return ++fi ++ ++# If the completion file doesn't exist yet, we need to autoload it and ++# bind it to `gcx`. Otherwise, compinit will have already done that. ++if [[ ! -f "$ZSH_CACHE_DIR/completions/_gcx" ]]; then ++ typeset -g -A _comps ++ autoload -Uz _gcx ++ _comps[gcx]=_gcx ++fi ++ ++zmodload -F zsh/files b:zf_mv ++() { ++ local TMPPREFIX="$ZSH_CACHE_DIR/completions/_gcx" ++ zf_mv -f -- =( gcx completion zsh ) "$TMPPREFIX" ++} &| diff --git a/tasks/ohmyzsh__ohmyzsh-13950/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-13950/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8490ebacda3bba810908ae3e3aa9430afaaa94eb --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13950/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b54a71977574cfcf659cc2f15a5e6422f17a8da7 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-13950/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-13950/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13950/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-13951/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-13951/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..66a7cd489c7d78a355db7b0d040cfa8aa196a677 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13951/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 87d4d40418438037e6e7576946cffa755d9b7fdf 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 87d4d40418438037e6e7576946cffa755d9b7fdf \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 87d4d40418438037e6e7576946cffa755d9b7fdf \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-13951/instruction.md b/tasks/ohmyzsh__ohmyzsh-13951/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..825c007a953726a167fa1f64441503d84249bfd3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13951/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** fix(jj): deprecated destination arg with onto + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- The `--destination` / `-d` arguments were renamed to `--onto` / `-o` in v36: https://docs.jj-vcs.dev/v0.36.0/changelog/#deprecations_1 so this PR updates the outdated use here :) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `87d4d4041843`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13951/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-13951/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..47a8194cb80a230ac4d843b445b337daf93214f5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13951/solution/patch.diff @@ -0,0 +1,41 @@ +diff --git a/plugins/jj/README.md b/plugins/jj/README.md +index c9e490ed..6e671697 100644 +--- a/plugins/jj/README.md ++++ b/plugins/jj/README.md +@@ -55,7 +55,7 @@ plugins=(... jj) + | jjopl | `jj op log` | + | jjor | `jj op restore` | + | jjrb | `jj rebase` | +-| jjrbm | `jj rebase -d "trunk()"` | ++| jjrbm | `jj rebase -o "trunk()"` | + | jjrs | `jj restore` | + | jjrt | `cd "$(jj root \|\| echo .)"` | + | jjs | `jj show` | +@@ -120,10 +120,10 @@ that. + + ### Git async-prompt compatibility + +-If you use a wrapper function that calls `git_prompt_info` (as shown above), it won't work with +-the default git async-prompt mode. This is because async-prompt only registers its background worker +-when it detects `$(git_prompt_info)` literally in your prompt variables. A wrapper like +-`$(_my_theme_vcs_info)` won't match, so the async output stays empty. ++If you use a wrapper function that calls `git_prompt_info` (as shown above), it won't work with the default ++git async-prompt mode. This is because async-prompt only registers its background worker when it detects ++`$(git_prompt_info)` literally in your prompt variables. A wrapper like `$(_my_theme_vcs_info)` won't match, ++so the async output stays empty. + + To fix this, add one of the following to your `.zshrc` **before** Oh My Zsh is sourced: + +diff --git a/plugins/jj/jj.plugin.zsh b/plugins/jj/jj.plugin.zsh +index 90b8d7b0..f1217608 100644 +--- a/plugins/jj/jj.plugin.zsh ++++ b/plugins/jj/jj.plugin.zsh +@@ -81,7 +81,7 @@ alias jjop='jj op' + alias jjopl='jj op log' + alias jjor='jj op restore' + alias jjrb='jj rebase' +-alias jjrbm='jj rebase -d "trunk()"' ++alias jjrbm='jj rebase -o "trunk()"' + alias jjrs='jj restore' + alias jjrt='cd "$(jj root || echo .)"' + alias jjs='jj show' diff --git a/tasks/ohmyzsh__ohmyzsh-13951/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-13951/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13951/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-13951/task.toml b/tasks/ohmyzsh__ohmyzsh-13951/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..777ec5be47086be2850861fe0cb10502be06e4f2 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13951/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-13951" +description = "fix(jj): deprecated destination arg with onto" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "87d4d40418438037e6e7576946cffa755d9b7fdf" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/13951" +source_access = "auto" +built_at = "2026-11-16T16:09:56.961707+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9713752ef18370b0ed4f55207cd9eac799824045b5bb8119cd67c928ff7b43da" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-10T11:21:29Z" +diff_format = "unified" +context_files = [ + "plugins/jj/README.md", + "plugins/jj/jj.plugin.zsh", +] +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.960068+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d9a574f08b30637806fca5b19b64d1d6b6b45cc386d23aa12a524763d6a3add4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-13951/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-13951/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13951/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-13951/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-13951/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..825c007a953726a167fa1f64441503d84249bfd3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13951/tests/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** fix(jj): deprecated destination arg with onto + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- The `--destination` / `-d` arguments were renamed to `--onto` / `-o` in v36: https://docs.jj-vcs.dev/v0.36.0/changelog/#deprecations_1 so this PR updates the outdated use here :) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `87d4d4041843`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13951/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-13951/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..47a8194cb80a230ac4d843b445b337daf93214f5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13951/tests/oracle.patch @@ -0,0 +1,41 @@ +diff --git a/plugins/jj/README.md b/plugins/jj/README.md +index c9e490ed..6e671697 100644 +--- a/plugins/jj/README.md ++++ b/plugins/jj/README.md +@@ -55,7 +55,7 @@ plugins=(... jj) + | jjopl | `jj op log` | + | jjor | `jj op restore` | + | jjrb | `jj rebase` | +-| jjrbm | `jj rebase -d "trunk()"` | ++| jjrbm | `jj rebase -o "trunk()"` | + | jjrs | `jj restore` | + | jjrt | `cd "$(jj root \|\| echo .)"` | + | jjs | `jj show` | +@@ -120,10 +120,10 @@ that. + + ### Git async-prompt compatibility + +-If you use a wrapper function that calls `git_prompt_info` (as shown above), it won't work with +-the default git async-prompt mode. This is because async-prompt only registers its background worker +-when it detects `$(git_prompt_info)` literally in your prompt variables. A wrapper like +-`$(_my_theme_vcs_info)` won't match, so the async output stays empty. ++If you use a wrapper function that calls `git_prompt_info` (as shown above), it won't work with the default ++git async-prompt mode. This is because async-prompt only registers its background worker when it detects ++`$(git_prompt_info)` literally in your prompt variables. A wrapper like `$(_my_theme_vcs_info)` won't match, ++so the async output stays empty. + + To fix this, add one of the following to your `.zshrc` **before** Oh My Zsh is sourced: + +diff --git a/plugins/jj/jj.plugin.zsh b/plugins/jj/jj.plugin.zsh +index 90b8d7b0..f1217608 100644 +--- a/plugins/jj/jj.plugin.zsh ++++ b/plugins/jj/jj.plugin.zsh +@@ -81,7 +81,7 @@ alias jjop='jj op' + alias jjopl='jj op log' + alias jjor='jj op restore' + alias jjrb='jj rebase' +-alias jjrbm='jj rebase -d "trunk()"' ++alias jjrbm='jj rebase -o "trunk()"' + alias jjrs='jj restore' + alias jjrt='cd "$(jj root || echo .)"' + alias jjs='jj show' diff --git a/tasks/ohmyzsh__ohmyzsh-13951/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-13951/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3007348b30edf787046a068dae4d49d323c3585a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13951/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 87d4d40418438037e6e7576946cffa755d9b7fdf > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-13951/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-13951/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13951/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-13957/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-13957/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5ab936088be9150cf324c8f13f0dde7758d61cfe --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13957/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b54a71977574cfcf659cc2f15a5e6422f17a8da7 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b54a71977574cfcf659cc2f15a5e6422f17a8da7 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b54a71977574cfcf659cc2f15a5e6422f17a8da7 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-13957/instruction.md b/tasks/ohmyzsh__ohmyzsh-13957/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b7ad072426c346f5448b561b54c863f3eb388400 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13957/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** chore(z): update to version 102fb780 + +## Description + +## Description + +Update for **z plugin**: update to version . +Check out the [list of changes](https://github.com/agkozak/zsh-z/compare/agkozak:acd0e19...agkozak:102fb78). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b54a71977574`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13957/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-13957/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f1c2ed06dc365d040ac616213d5349045ab7c921 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13957/solution/patch.diff @@ -0,0 +1,2027 @@ +diff --git a/.github/dependencies.yml b/.github/dependencies.yml +index b2440fa7..96d9991a 100644 +--- a/.github/dependencies.yml ++++ b/.github/dependencies.yml +@@ -46,9 +46,10 @@ dependencies: + plugins/z: + branch: master + repo: agkozak/zsh-z +- version: acd0e1984df350c189f8f9c4956ec586b6c73fca ++ version: 102fb78036ed76feedf623907483691777a1d510 + precopy: | + set -e ++ rm -r tests + test -e README.md && mv -f README.md MANUAL.md + postcopy: | + set -e +diff --git a/plugins/z/MANUAL.md b/plugins/z/MANUAL.md +index 420535b2..1c8a1d22 100644 +--- a/plugins/z/MANUAL.md ++++ b/plugins/z/MANUAL.md +@@ -2,20 +2,26 @@ + + [![MIT License](img/mit_license.svg)](https://opensource.org/licenses/MIT) + ![Zsh version 4.3.11 and higher](img/zsh_4.3.11_plus.svg) ++![Version](https://img.shields.io/github/v/release/agkozak/zsh-z) ++![Workflow Status](https://github.com/agkozak/zsh-z/actions/workflows/test.yml/badge.svg) + [![GitHub stars](https://img.shields.io/github/stars/agkozak/zsh-z.svg)](https://github.com/agkozak/zsh-z/stargazers) + + ![Zsh-z demo](img/demo.gif) + + Zsh-z is a command-line tool that allows you to jump quickly to directories that you have visited frequently or recently -- but most often a combination of the two (a concept known as ["frecency"](https://en.wikipedia.org/wiki/Frecency)). It works by keeping track of when you go to directories and how much time you spend in them. Based on this data, it predicts where you want to go when you type a partial string. For example, `z src` might take you to `~/src/zsh`. `z zsh` might also get you there, and `z c/z` might prove to be even more specific -- it all depends on your habits and how long you have been using Zsh-z to build up a database. After using Zsh-z for a little while, you will get to where you want to be by typing considerably less than you would need to if you were using `cd`. + +-Zsh-z is a native Zsh port of [`rupa/z`](https://github.com/rupa/z), a tool written for `bash` and Zsh that uses embedded `awk` scripts to do the heavy lifting. `rupa/z` was my most used command-line tool for a couple of years. I decided to translate it, `awk` parts and all, into pure Zsh script, to see if by eliminating calls to external tools (`awk`, `sort`, `date`, `sed`, `mv`, `rm`, and `chown`) and reducing forking through subshells I could make it faster. The performance increase is impressive, particularly on systems where forking is slow, such as Cygwin, MSYS2, and WSL. I have found that in those environments, switching directories using Zsh-z can be over 100% faster than it is using `rupa/z`. ++Zsh-z is a native Zsh port of [`rupa/z`](https://github.com/rupa/z), a tool written for `bash` and Zsh that uses embedded `awk` scripts to do the heavy lifting. `rupa/z` was my most used command-line tool for a couple of years. I decided to translate it, `awk` parts and all, into pure Zsh script, to see if by eliminating calls to external tools (`awk`, `sort`, `date`, `sed`, `mv`, `rm`, and `chown`) and reducing forking through subshells I could make it faster. The performance increase is impressive, particularly on systems where forking is slow, such as Cygwin, MSYS2, and WSL. + +-There is also a significant stability improvement. Race conditions have always been a problem with `rupa/z`, and users of that utility occasionally lose their `~/.z` databases. By having Zsh-z only use Zsh (`rupa/z` uses a hybrid shell code standard that works on `bash` as well), I have been able to implement a `zsh/system`-based file-locking mechanism similar to [the one @mafredri once proposed for `rupa/z`](https://github.com/rupa/z/pull/199). It is now nearly impossible to crash the database. ++There is also a significant stability improvement. Race conditions have always been a problem with `rupa/z`, and users of that utility occasionally lose their `~/.z` databases. By having Zsh-z only use Zsh (`rupa/z` uses a hybrid shell code standard that works on `bash` as well), I have been able to implement a `zsh/system`-based file-locking mechanism. It is now nearly impossible to crash the database. + +-There are other, smaller improvements which I document below in [Improvements and Fixes](#improvements-and-fixes). For instance, tab completions are now sorted by frecency by default rather than alphabetically (the latter behavior can be restored if you like it -- [see below](#settings)). ++There are other, smaller improvements which I document below in [Other Improvements to the Original Functionality of `rupa/z`](#other-improvements-to-the-original-functionality-of-rupaz). For instance, tab completions are now sorted by frecency by default rather than alphabetically (the latter behavior can be restored if you like it -- [see below](#settings)). + + Zsh-z is a drop-in replacement for `rupa/z` and will, by default, use the same database (`~/.z`, or whatever database file you specify), so you can go on using `rupa/z` when you launch `bash`. + ++> ### Zsh-z v2.0 ++> ++> **v2.0 is the most significant release in the project's history.** It is faster than ever at adding, searching, and listing on modern Zsh; it never makes your prompt wait on database writes -- on any platform; it hardens those writes against corruption and against prying eyes; and it makes tab completion "just work" even under `setopt COMPLETE_ALIASES`. See [**v2.0**](#v20) in the News below for the full rundown, and [Performance](#performance) for the benchmarks. ++ + ## Table of Contents + - [News](#news) + - [Installation](#installation) +@@ -23,16 +29,45 @@ Zsh-z is a drop-in replacement for `rupa/z` and will, by default, use the same d + - [Settings](#settings) + - [Case Sensitivity](#case-sensitivity) + - [`ZSHZ_UNCOMMON`](#zshz_uncommon) ++- [`ZSHZ_OWNER`](#zshz_owner) + - [Making `--add` work for you](#making---add-work-for-you) +-- [Other Improvements to the Original Functionality of `rupa/z`](#other-improvements-to-the-original-functionality-of-rupa-z) ++- [Performance](#performance) ++- [Other Improvements to the Original Functionality of `rupa/z`](#other-improvements-to-the-original-functionality-of-rupaz) + - [Migrating from Other Tools](#migrating-from-other-tools) + - [`COMPLETE_ALIASES`](#complete_aliases) + + ## News + ++### v2.0 (August 14, 2026) ++ ++Version **2.0** is a major step forward, and these are the changes most worth knowing about: ++ ++- **Zsh-z is even faster than before.** Version 2.0 builds on Zsh-z's past successes in optimizing adding to the datafile -- something it does at virtually every prompt -- by streamlining searching and listing, as well. See [Performance](#performance) for the numbers. ++- **Database writes never block your prompt** -- on any platform. The per-prompt `--add` has long run in the background on most systems, but Cygwin and MSYS2 did the write in the foreground, because backgrounding there cost a wrapper subshell plus a job. `--add` now runs as a single disowned job (`&!`) everywhere: one fork, no wrapper subshell, no job-control noise. On Cygwin and MSYS2 that turns a foreground write whose cost grows with your datafile (~30 ms at 300 entries, ~300 ms at 1,000) into a flat ~10-12 ms fork. Elsewhere it halves the forks per prompt. ++- **Safer, crash-resistant concurrent writes.** Writes are now guarded by a dedicated, stable lockfile using `zsh/system` file locking, with a bounded wait for lock acquisition (the new [`ZSHZ_LOCK_TIMEOUT`](#settings), default `1` second). Write errors are handled gracefully, and locks are always released even if a write is interrupted. On Cygwin and MSYS2 a write is also retried briefly if Windows refuses it: a virus scanner or the search indexer that opens the database in the instant between its being written and its being moved into place makes the move fail, which used to lose that one directory silently. Zsh-z now retries the move briefly. ++- **Your database file now has `600` permissions** -- readable and writable only by you -- so that other users on a shared system cannot read your directory history ([#92](https://github.com/agkozak/zsh-z/issues/92)). On Zsh 5+ this uses the in-process `zf_chmod` builtin; on Zsh 4.3.11 it uses a `umask`-in-a-subshell technique that avoids the fork-and-exec of an external `chmod`. ++- **`COMPLETE_ALIASES` works automatically in normal setups.** Tab completion no longer breaks when you have `setopt COMPLETE_ALIASES` enabled. Zsh-z registers the alias automatically on the first Tab press, so the manual `compdef` line that earlier versions required is no longer necessary. [See below](#complete_aliases). ++- **Fixed a `can't clobber parameter tmpfd` error on some Zsh builds.** On certain Zsh builds, every database write could fail with `can't clobber parameter tmpfd containing file descriptor 0`, leaving an error at each new prompt. The file descriptor used for the temporary database file is now held in an unset scalar rather than one seeded with `0`, so the write never trips Zsh's file-descriptor-clobber guard ([#81](https://github.com/agkozak/zsh-z/issues/81)). ++- **A misconfigured database file no longer closes your shell -- or nags you at every prompt.** When `ZSHZ_DATA` points at a directory, or names a file without a directory, Zsh-z now reports the problem and returns instead of calling `exit`. The per-prompt `--add` stays quiet about it, so you are told once, when you actually run `z`, rather than at every prompt ([#103](https://github.com/agkozak/zsh-z/issues/103); props @ahjota). ++- **`z -x` can now remove the entry for a directory that no longer exists -- and can no longer crash Zsh 4.3.11.** The removal target used to have to exist on disk, so a database entry whose directory had been deleted -- exactly the entry you most want gone -- could not be removed. `z -x /deleted/dir` (and `z -xR`) now canonicalizes the argument without requiring it to exist, resolving symlinks in as much of the path as is still present. The same change fixes a crash on Zsh 4.3.11, where an upstream bug makes `${x:A}` segfault when the top-level component of the path is missing: `z -x /gone/sub` -- or a `ZSHZ_DATA` pointing into a missing top-level directory -- could kill the shell there. ++- **More robust startup and operation.** A version check on an unsupported Zsh no longer risks exiting your interactive shell. ++ ++#### Smaller changes you may notice ++ ++None of these should need any action from you, but they are the things a v1 user is most likely to spot: ++ ++- **`-r` and `-t` can no longer be combined.** They name mutually exclusive sort orders -- rank versus recency -- so `z -rt foo` was always contradictory, and `-t` silently took precedence. It is now rejected with an error message instead of silently picking one. ++- **A lockfile appears next to your database.** Writes are serialized through `~/.z.lock` (or `$ZSHZ_DATA` plus `.lock`). It is created `600`, it stays empty, and it is deliberately never deleted -- removing a lockfile that another shell has already opened would reintroduce the very race it exists to prevent. Where `zsh/system` is missing and `zsystem flock` is therefore unavailable -- MobaXterm's cut-down Cygwin is the case in practice -- you will see a short-lived `~/.z.lock.d` **directory** instead, which is created and removed for each write. See [`ZSHZ_LOCK_TIMEOUT`](#settings) for how that fallback behaves. ++- **An existing database gets tightened to `600` on the next write.** If your `~/.z` predates this release and is `644`, the first write will re-mode it. This is the [#92](https://github.com/agkozak/zsh-z/issues/92) fix applied to databases you already have, not just newly created ones. Setting the mode is treated as part of the write rather than a courtesy afterwards: if it cannot be done, the write is abandoned and reports failure instead of publishing a database that anyone on the machine could read. ++ ++The dated entries below remain the historical record of changes leading up to v2.0. ++ +
      +- Here are the latest features and updates. ++ Here are the older features and updates. + ++- May 6, 2026 ++ + Zsh-z will now handle paths with dollar signs (`$`) in them. ++ + Workaround for Zsh emulating `sh`/`bash`/`ksh`. + - May 1, 2026 + + Various tab completion bugs resolved. + - April 27, 2026 +@@ -90,7 +125,7 @@ Zsh-z is a drop-in replacement for `rupa/z` and will, by default, use the same d + - February 15, 2021 + + Ranks are displayed the way `rupa/z` now displays them, i.e. as large integers. This should help Zsh-z to integrate with other tools. + - January 31, 2021 +- + Zsh-z is now efficient enough that, on MSYS2 and Cygwin, it is faster to run it in the foreground than it is to fork a subshell for it. ++ + Zsh-z is now efficient enough that, on MSYS2 and Cygwin, it is faster to run it in the foreground than it is to fork a subshell for it. (Behavior superseded in v2.0.) + + `_zshz_precmd` simply returns if `PWD` is `HOME` or in `ZSHZ_EXCLUDE_DIRS`, rather than waiting for `zshz` to do that. + - January 17, 2021 + + Made sure that the `PUSHD_IGNORE_DUPS` option is respected. +@@ -121,11 +156,11 @@ This plugin can be installed simply by putting the various files in a directory + + source /path/to/zsh-z.plugin.zsh + +-For tab completion to work, `_zshz` *must* be in the same directory as `zsh-z.plugin.zsh`, and you will want to have loaded `compinit`. The frameworks handle this themselves. If you are not using a framework, put ++Tab completion requires `compinit`. `_zshz` *must* also be in the same directory as `zsh-z.plugin.zsh`. The frameworks handle both of these requirements, but if you are not using a framework, put + + autoload -U compinit; compinit + +-in your `.zshrc` somewhere below where you source `zsh-z.plugin.zsh`. ++in your `.zshrc` somewhere below where you source `zsh-z.plugin.zsh` -- the plugin adds its directory to `fpath` at source time, and `compinit` needs to see it there in order to find `_zshz`. + + If you add + +@@ -195,7 +230,7 @@ Add a backslash to the end of the last line and add `'zsh-z'` to the list, e.g., + Then relaunch `zsh`. + + ### For [zcomet](https://github.com/agkozak/zcomet) users +- ++ + Simply add + + zcomet load agkozak/zsh-z +@@ -235,7 +270,7 @@ Add the line + + to your `.zshrc`. + +-Zsh-z supports `zinit`'s `unload` feature; just run `zinit unload agkozak/zsh-z` to restore the shell to its state before Zsh-z was loaded. ++Zsh-z supports `zinit`'s `unload` feature; just run `zinit unload agkozak/zsh-z` to restore the shell to its state before Zsh-z was loaded. It gives back only what it took: the `fpath` entry is removed only if Zsh-z was the one that added it, so a directory your plugin manager put there is left alone, and the Tab-completion mapping is dropped only while it still points at Zsh-z's own completer. + + ### For [Znap](https://github.com/marlonrichert/zsh-snap) users + +@@ -274,6 +309,7 @@ to install Zsh-z. + + Zsh-z has environment variables (they all begin with `ZSHZ_`) that change its behavior if you set them. You can also keep your old ones if you have been using `rupa/z` (whose environment variables begin with `_Z_`). + ++* `ZSHZ_CASE` can be `ignore`, for case-insensitive matching, or `smart`, for Vim-like `smartcase` matching; [see below](#case-sensitivity) (default: empty, i.e., a case-sensitive match is tried first, then a case-insensitive one) + * `ZSHZ_CMD` changes the command name (default: `z`) + * `ZSHZ_CD` specifies the default directory-changing command (default: `builtin cd`) + * `ZSHZ_COMPLETION` can be `'frecent'` (default) or `'legacy'`, depending on whether you want your completion results sorted according to frecency or simply sorted alphabetically +@@ -281,9 +317,10 @@ Zsh-z has environment variables (they all begin with `ZSHZ_`) that change its be + * `ZSHZ_ECHO` displays the new path name when changing directories (default: `0`) + * `ZSHZ_EXCLUDE_DIRS` is an array of directories to keep out of the database (default: empty) + * `ZSHZ_KEEP_DIRS` is an array of directories that should not be removed from the database, even if they are not currently available (useful when a drive is not always mounted) (default: empty) ++* `ZSHZ_LOCK_TIMEOUT` is the number of seconds to wait for the database lock before giving up on a write (default: `1`). Where `zsh/system` is unavailable and `zsystem flock` cannot be used -- MobaXterm's cut-down Cygwin, for instance -- Zsh-z serializes writes with an atomic `mkdir` on `~/.z.lock.d` instead, and this setting bounds the wait the same way. That fallback has no equivalent of the kernel releasing a lock when its holder dies, so a lock directory older than 30 seconds is treated as abandoned and cleared; a write takes milliseconds, so nothing legitimate is ever that old. A write that times out is dropped silently -- the automatic `precmd` add is best-effort -- so if the database seems to stop updating, the lock is probably contended: run `z --add .` by hand and check `$?`. A `2` is a lock-acquisition timeout, which confirms contention -- look for a stale process holding `~/.z.lock` (or a leftover `~/.z.lock.d` directory on the fallback path), or raise this setting. A `1` is something else entirely, usually a permissions or ownership problem, such as a root-owned `~/.z` or `~/.z.lock` left behind by an earlier `sudo -s` session. + * `ZSHZ_MAX_SCORE` is the maximum combined score the database entries can have before they begin to age and potentially drop out of the database (default: 9000) + * `ZSHZ_NO_RESOLVE_SYMLINKS` prevents symlink resolution (default: `0`) +-* `ZSHZ_OWNER` allows usage when in `sudo -s` mode (default: empty) ++* `ZSHZ_OWNER` is the username the database belongs to; set it to your own login name to keep `z` working in a root shell, such as under `sudo -E -s`; [see below](#zshz_owner) (default: empty) + * `ZSHZ_TILDE` displays the name of the `HOME` directory as a `~` (default: `0`) + * `ZSHZ_TRAILING_SLASH` makes it so that a search pattern ending in `/` can match the final element in a path; e.g., `z foo/` can match `/path/to/foo` (default: `0`) + * `ZSHZ_UNCOMMON` changes the logic used to calculate the directory jumped to; [see below](#zshz_uncommon) (default: `0`) +@@ -319,6 +356,12 @@ then there is no common prefix. In this case, `z code` will simply send you to t + + You may enable an alternate, experimental behavior by setting `ZSHZ_UNCOMMON=1`. If you do that, Zsh-z will not jump to a common prefix, even if one exists. Instead, it chooses the highest-ranking match -- but it drops any subdirectories that do not include the search term. So if you type `z bat` and `/home/me/code/bat` is the best match, that is exactly where you will end up. If, however, you had typed `z code` and the best match was also `/home/me/code/bat`, you would have ended up in `/home/me/code` (because `code` was what you had searched for). This feature is still in development, and feedback is welcome. + ++## `ZSHZ_OWNER` ++ ++If you are using `root` privileges while keeping your personal home directory as `HOME` (as is the case with `sudo -E -s`), conflicts with file ownership arise. You can resolve them by using `ZSHZ_OWNER`. If you set this variable to your username, Zsh-z will be able to use your personal datafile, restoring its proper ownership with every write. ++ ++Setting `ZSHZ_OWNER` makes one thing stricter, because a privileged shell is then writing to a path that an unprivileged user controls: Zsh-z follows a symlink on the way to the datafile -- the file itself, or any parent directory -- only if `root` owns the link, and reports an error instead of writing otherwise. Symlinked system directories, such as `/home` → `/usr/home` on the BSDs or `/var` → `/private/var` on macOS, belong to root and still resolve. With `ZSHZ_OWNER` unset none of this applies: a symlinked `~/.z` is followed exactly as before, so pointing it at synced storage keeps working. ++ + ## Making `--add` Work for You + + Zsh-z internally uses the `--add` option to add paths to its database. @zachriggle pointed out to me that users might want to use `--add` themselves, so I have altered it a little to make it more user-friendly. +@@ -331,9 +374,33 @@ A good example might involve a directory tree that has Git repositories within i + + (As a Zsh user, I tend to use `**` instead of `find`, but it is good to see how deep your directory trees go before doing that.) + ++## Performance ++ ++One of the goals of the rewrite that culminated in v2.0 was to make Zsh-z simultaneously more stable and faster. On modern Zsh, Zsh-z outpaces `rupa/z`'s `z.sh` at adding, searching, and listing. Representative figures (N = 200 database entries, medians of seven interleaved runs on a Core i7-12700 desktop under WSL2): ++ ++**Modern Zsh (5.9) -- Zsh-z vs. `rupa/z`:** ++ ++| Operation | `rupa/z` (`z.sh`) | Zsh-z | Winner | ++| --------- | ----------------- | ----------- | ----------------- | ++| `add` | 6.25 ms/op | 1.99 ms/op | **Zsh-z** ~3.14x | ++| `search` | 6.51 ms/op | 3.62 ms/op | **Zsh-z** ~1.80x | ++| `list` | 8.93 ms/op | 4.36 ms/op | **Zsh-z** ~2.05x | ++ ++**Zsh 4.3.11 (the oldest supported release) -- Zsh-z vs. `rupa/z`:** ++ ++| Operation | `rupa/z` (`z.sh`) | Zsh-z | Winner | ++| --------- | ----------------- | ----------- | ----------------- | ++| `add` | 5.00 ms/op | 2.92 ms/op | **Zsh-z** ~1.71x | ++| `search` | 4.93 ms/op | 4.47 ms/op | **Zsh-z** ~1.10x | ++| `list` | 7.92 ms/op | 6.08 ms/op | **Zsh-z** ~1.30x | ++ ++Removal is absent from these tables: in `rupa/z`, the per-prompt hook re-adds the current directory right after `z -x` removes it, so the two implementations' `-x` are not doing comparable work. ++ ++Relative to the previous generation of Zsh-z, the v2.0 read path is dramatically faster -- on modern Zsh, listing the whole database is about 2.4x faster and searching about 1.6x faster. ++ + ## Other Improvements to the Original Functionality of `rupa/z` + +-* `z -x` works, with the help of `chpwd_functions`. ++* `z -x` works: a directory you remove stays removed. + * Zsh-z is compatible with Solaris. + * Zsh-z uses the "new" `zshcompsys` completion system instead of the old `compctl` one. + * No error message is displayed when the database file has not yet been created. +@@ -355,12 +422,10 @@ If you are coming to Zsh-z (or even to the original `rupa/z`, for that matter) f + + ## `COMPLETE_ALIASES` + +-`z`, or any alternative you set up using `$ZSHZ_CMD` or `$_Z_CMD`, is an alias. `setopt COMPLETE_ALIASES` divorces the tab completion for aliases from the underlying commands they invoke, so if you enable `COMPLETE_ALIASES`, tab completion for Zsh-z will be broken. You can get it working again, however, by adding under +- +- setopt COMPLETE_ALIASES ++`z`, or any alternative you set up using `$ZSHZ_CMD` or `$_Z_CMD`, is an alias. `setopt COMPLETE_ALIASES` divorces the tab completion for aliases from the underlying commands they invoke, which historically broke Zsh-z's tab completion. Zsh-z now handles this automatically: the first Tab press registers the alias name with `_zshz` so completion works under `COMPLETE_ALIASES` without any extra setup. + +-the line ++That registration happens inside Zsh-z's own Tab widget. If a plugin loaded after Zsh-z replaces the Tab binding without invoking the previous widget, Zsh-z's widget never runs and the registration does not happen. Under `COMPLETE_ALIASES`, you would then have no completion for `z`. Once `compinit` has run, adding + + compdef _zshz ${ZSHZ_CMD:-${_Z_CMD:-z}} + +-That will re-bind `z` or the command of your choice to the underlying Zsh-z function. ++below `setopt COMPLETE_ALIASES` in your `.zshrc` fixes that, and it is harmless if the automatic registration has already run. +diff --git a/plugins/z/_z b/plugins/z/_z +index a109841d..09e70af4 100644 +--- a/plugins/z/_z ++++ b/plugins/z/_z +@@ -1,6 +1,6 @@ + #compdef zshz ${ZSHZ_CMD:-${_Z_CMD:-z}} + # +-# Zsh-z - jump around with Zsh - A native Zsh version of z without awk, sort, ++# Zsh-z - jump around with Zsh - A native Zsh version of rupa/z without awk, sort, + # date, or sed + # + # https://github.com/agkozak/zsh-z +@@ -24,11 +24,7 @@ + # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + # SOFTWARE. +-# +-# z (https://github.com/rupa/z) is copyright (c) 2009 rupa deadwyler and +-# licensed under the WTFPL license, Version 2.a +-# +-# shellcheck shell=ksh ++################################################################################ + + ############################################################ + # Zsh-z COMPLETIONS +diff --git a/plugins/z/z.plugin.zsh b/plugins/z/z.plugin.zsh +index 6df49822..d922fa77 100644 +--- a/plugins/z/z.plugin.zsh ++++ b/plugins/z/z.plugin.zsh +@@ -1,6 +1,6 @@ + ################################################################################ +-# Zsh-z - jump around with Zsh - A native Zsh version of z without awk, sort, +-# date, or sed ++# Zsh-z - jump around with Zsh - A native Zsh version of rupa/z without awk, ++# sort, date, or sed + # + # https://github.com/agkozak/zsh-z + # +@@ -24,9 +24,6 @@ + # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + # SOFTWARE. + # +-# z (https://github.com/rupa/z) is copyright (c) 2009 rupa deadwyler and +-# licensed under the WTFPL license, Version 2. +-# + # Zsh-z maintains a jump-list of the directories you actually use. + # + # INSTALL: +@@ -57,22 +54,45 @@ + # ZSHZ_COMPLETION -> completion method (default: 'frecent'; 'legacy' for + # alphabetic sorting) + # ZSHZ_DATA -> name of datafile (default: ~/.z) ++# ZSHZ_DEBUG -> if set, turn on debugging aids: WARN_CREATE_GLOBAL while the ++# command runs and per-function warnings (functions -W) at load time ++# (default: unset) ++# ZSHZ_ECHO -> if 1, print the directory name after jumping to it (default: 0) + # ZSHZ_EXCLUDE_DIRS -> array of directories to exclude from your database + # (default: empty) + # ZSHZ_KEEP_DIRS -> array of directories that should not be removed from the + # database, even if they are not currently available (default: empty) ++# ZSHZ_LOCK_TIMEOUT -> seconds to wait for the lockfile before giving up ++# (default: 1) + # ZSHZ_MAX_SCORE -> maximum combined score the database entries can have + # before beginning to age (default: 9000) + # ZSHZ_NO_RESOLVE_SYMLINKS -> '1' prevents symlink resolution + # ZSHZ_OWNER -> your username (if you want use Zsh-z while using sudo -s) ++# ZSHZ_TILDE -> if 1, display ~ in place of the full $HOME path in output ++# (default: 0) ++# ZSHZ_TRAILING_SLASH -> if 1, a query ending in / matches at the end of a ++# directory path (default: 0) + # ZSHZ_UNCOMMON -> if 1, do not jump to "common directories," but rather drop + # subdirectories based on what the search string was (default: 0) + ################################################################################ + +-autoload -U is-at-least ++# Minimalistic solution to allow this plugin to keep running under sh/bash/ksh ++# emulation while continuing to use Zsh-only syntax features. `emulate zsh -c' ++# evaluates its argument as code, so the script's own path -- `${(%):-%N}' -- ++# must be `${(q)}'-quoted; otherwise an install directory containing spaces or ++# other shell-special characters (common on Cygwin/MSYS2 and macOS, where a ++# home directory can be "C:\Users\John Smith" or "/Users/John Smith") would be ++# word-split and the plugin would silently fail to re-source. ++if [[ -o KSH_ARRAYS || -o SH_WORD_SPLIT ]]; then ++ emulate zsh -c "source ${(q)${(%):-%N}}" ++ return $? ++fi ++ ++autoload -Uz is-at-least + + if ! is-at-least 4.3.11; then +- print "Zsh-z requires Zsh v4.3.11 or higher." >&2 && exit ++ print "Zsh-z requires Zsh v4.3.11 or higher." >&2 ++ return 1 2> /dev/null || exit 1 + fi + + ############################################################ +@@ -99,6 +119,56 @@ With no ARGUMENT, list the directory history in ascending rank. + fold -s -w $(( COLUMNS > 0 ? COLUMNS : 80 )) >&2 + } + ++############################################################ ++# Canonicalize a path in the manner of `:A' -- normalize it ++# lexically as `:a' does, then resolve symlinks -- without ++# requiring any of the path to exist. ++# ++# `${x:A}' itself cannot be trusted with a missing path on ++# Zsh 4.3.11: when the top-level component of $x does not ++# exist (`/gone/sub'), the realpath machinery segfaults the ++# shell (upstream bug, 4.3.11 only; deeper missing ++# components are handled correctly on every version). So ++# apply `:A' only to the deepest ancestor of the path that ++# exists -- `:A' on an existing path is safe everywhere -- ++# and reattach the missing components verbatim. That ++# reproduces `:A' exactly: `:A' resolves the symlinks in the ++# existing prefix and carries the nonexistent tail ++# unchanged, and the tail cannot contain live symlinks ++# precisely because it does not exist. (A broken symlink ++# stops the ancestor walk without being resolved -- `-e' ++# fails on one -- which also matches `:A', which leaves ++# broken symlinks unresolved.) ++# ++# Arguments: ++# $1 The path to canonicalize ++# ++# Returns the canonical path in $REPLY. ++############################################################ ++_zshz_realpath() { ++ local dir=${1:a} ++ local -a tail ++ ++ # `:h' at its fixed point (`/', or `//' where the OS treats that as ++ # distinct) can climb no higher; if even that much of the path does not ++ # exist, settle for the lexical normalization rather than hand `:A' ++ # something dangerous. ++ while [[ ! -e $dir && $dir != "${dir:h}" ]]; do ++ tail=( "${dir:t}" "${tail[@]}" ) ++ dir=${dir:h} ++ done ++ [[ -e $dir ]] && dir=${dir:A} ++ ++ # `typeset -g': REPLY belongs to the caller by design. A plain assignment ++ # would trip WARN_NESTED_VAR under `ZSHZ_DEBUG', since _zshz_realpath is a ++ # top-level function and thus one of the ones `functions -W' marks. ++ if (( ${#tail} )); then ++ typeset -g REPLY=${dir%/}/${(j:/:)tail} ++ else ++ typeset -g REPLY=$dir ++ fi ++} ++ + # Load zsh/datetime module, if necessary + (( ${+EPOCHSECONDS} )) || zmodload zsh/datetime + +@@ -106,16 +176,26 @@ With no ARGUMENT, list the directory history in ascending rank. + typeset -gA ZSHZ + + # Fallback utilities in case Zsh lacks zsh/files (as is the case with MobaXterm) ++ZSHZ[CHMOD]='chmod' + ZSHZ[CHOWN]='chown' + ZSHZ[MV]='mv' + ZSHZ[RM]='rm' +-# Try to load zsh/files utilities ++ ++# Try to load zsh/files. zf_chown, zf_mv, and zf_rm are usually present in Zsh ++# 4.3.11. zf_chmod only became available in Zsh 5.0, so we load it separately ++# below. If zsh/files is not available at all, we silently fall back to the ++# external utilities chmod, chown, mv, and rm. + if [[ ${builtins[zf_chown]-} != 'defined' || + ${builtins[zf_mv]-} != 'defined' || + ${builtins[zf_rm]-} != 'defined' ]]; then + zmodload -F zsh/files b:zf_chown b:zf_mv b:zf_rm &> /dev/null + fi +-# Use zsh/files, if it is available ++ ++[[ ${builtins[zf_chmod]-} == 'defined' ]] || ++ zmodload -F zsh/files b:zf_chmod &> /dev/null ++ ++# Use zsh/files, if it is available. ++[[ ${builtins[zf_chmod]-} == 'defined' ]] && ZSHZ[CHMOD]='zf_chmod' + [[ ${builtins[zf_chown]-} == 'defined' ]] && ZSHZ[CHOWN]='zf_chown' + [[ ${builtins[zf_mv]-} == 'defined' ]] && ZSHZ[MV]='zf_mv' + [[ ${builtins[zf_rm]-} == 'defined' ]] && ZSHZ[RM]='zf_rm' +@@ -130,8 +210,44 @@ fi + # Determine if zsystem flock is available + zsystem supports flock &> /dev/null && ZSHZ[USE_FLOCK]=1 + +-# Determine if `print -v' is supported +-is-at-least 5.3.0 && ZSHZ[PRINTV]=1 ++# Windows only: how many times to retry a datafile rename that fails. ++# ++# On Cygwin and MSYS2, rename() fails with EBUSY or EACCES whenever another ++# process holds the tempfile or the datafile open without FILE_SHARE_DELETE -- ++# which is precisely what a virus scanner or the search indexer does to a file ++# in the moments after it is created. Since the write path below creates the ++# tempfile and renames it over the datafile microseconds later, that window is ++# wide open. The rename's stderr is discarded there, so a scan that lands in ++# the window silently loses an `--add' or a `-x': no message, no delay, just a ++# directory that never made it into the database. The condition clears in ++# milliseconds, so make a few more attempts before giving up. ++# ++# Everywhere else a failed rename means something real -- ENOSPC, EPERM, a ++# cross-device move -- that retrying cannot fix and would only add latency to, ++# so ZSHZ[MV_RETRIES] stays unset and the loops below make a single attempt, ++# exactly as before. ++# ++# zsh/zselect provides the sub-second delay between attempts without forking ++# /bin/sleep, whose fractional-seconds support is not portable in any case. ++# MobaXterm's cut-down Cygwin does not ship zsh/zselect, so there ++# ZSHZ[MV_RETRY_DELAY] stays unset and the retries happen back to back -- still ++# worth making, since the scanner's handle is often gone by the next attempt. ++# ++# Four retries at 50ms is deliberately modest rather than generous. The rename ++# runs while the lockfile is held, so every millisecond spent retrying is a ++# millisecond other writers spend waiting, and they give up after ++# ZSHZ_LOCK_TIMEOUT (1s by default) -- silently, since their adds are ++# best-effort too. A budget that outlasts a large fraction of that timeout ++# would trade one process's lost write for several others'. Measured on MSYS2 ++# against a handle held open with FILE_SHARE_READ, this recovers renames ++# blocked for up to ~0.3s, comfortably more than a scan of a file this small ++# takes. ++if [[ $OSTYPE == (cygwin|msys) ]]; then ++ ZSHZ[MV_RETRIES]=4 ++ [[ ${modules[zsh/zselect]-} == 'loaded' ]] || zmodload zsh/zselect &> /dev/null ++ # In hundredths of a second, per `zselect -t' ++ [[ ${builtins[zselect]-} == 'defined' ]] && ZSHZ[MV_RETRY_DELAY]=5 ++fi + + ############################################################ + # The Zsh-z Command +@@ -145,6 +261,7 @@ is-at-least 5.3.0 && ZSHZ[PRINTV]=1 + # ZSHZ_DEBUG + # ZSHZ_EXCLUDE_DIRS + # ZSHZ_KEEP_DIRS ++# ZSHZ_LOCK_TIMEOUT + # ZSHZ_MAX_SCORE + # ZSHZ_OWNER + # +@@ -163,42 +280,136 @@ zshz() { + # Allow the user to specify a custom datafile in $ZSHZ_DATA (or legacy $_Z_DATA) + local custom_datafile="${ZSHZ_DATA:-$_Z_DATA}" + ++ # $_zshz_quiet_add marks the automatic bookkeeping add that _zshz_precmd ++ # runs in a `&!' fork before every prompt (_zshz_precmd declares it `local', ++ # so it is visible here only through that one call). A fork cannot ++ # record anything in the parent shell, so it has no way to warn just once: ++ # an unusable $ZSHZ_DATA would otherwise put the same diagnostic on the ++ # terminal at every prompt for the life of the shell. Stay quiet on that ++ # path and leave the complaining to the entry points the user actually ++ # invoked -- including a hand-typed `z --add', which is not marked and so ++ # still reports. ++ local quiet ++ [[ -n ${_zshz_quiet_add-} ]] && quiet=1 ++ + # If a datafile was provided as a standalone file without a directory path +- # print a warning and exit ++ # print a warning and return + if [[ -n ${custom_datafile} && ${custom_datafile} != */* ]]; then +- print "ERROR: You configured a custom Zsh-z datafile (${custom_datafile}), but have not specified its directory." >&2 +- exit ++ (( quiet )) || ++ print "ERROR: You configured a custom Zsh-z datafile (${custom_datafile}), but have not specified its directory." >&2 ++ return 1 + fi + +- # If the user specified a datafile, use that or default to ~/.z +- # If the datafile is a symlink, it gets dereferenced +- local datafile=${${custom_datafile:-$HOME/.z}:A} ++ # Refuse a symlinked datafile while $ZSHZ_OWNER is set, rather than ++ # following it. That variable means root is acting for an unprivileged user ++ # -- the documented `sudo -s' setup -- and the resolution just below ++ # deliberately dereferences a link, so in that configuration Zsh-z would ++ # write the database wherever a name inside the user's own home points, with ++ # root's authority. Nothing has to be raced: the link is planted before the ++ # privileged shell ever starts. Unprivileged use crosses no such boundary and ++ # keeps the dereference, which is what makes pointing `.z' at synced storage ++ # work. ++ # ++ # Every component, not just the last. Resolution walks the whole path, so a ++ # symlinked *parent* redirects it just as effectively: with `link' -> `/etc' ++ # inside a user's home, a datafile of `~/link/passwd' resolves to ++ # `/etc/passwd' and root rewrites it. ++ # ++ # Judged by who owns each link rather than by its mere presence. Symlinked ++ # system directories are ordinary -- `/home' -> `/usr/home' on the BSDs, ++ # `/var' -> `/private/var' on macOS -- and refusing those would break Zsh-z ++ # under $ZSHZ_OWNER on those systems for nothing. Those are root's; what this ++ # has to reject is a link an unprivileged owner could have planted. `zstat ++ # -L' reports the link's own owner rather than its target's, which is the ++ # distinction `-O' cannot make. ++ if [[ -n ${ZSHZ_OWNER:-${_Z_OWNER}} ]]; then ++ local _zshz_df=${custom_datafile:-$HOME/.z} ++ [[ $_zshz_df == /* ]] || _zshz_df="$PWD/$_zshz_df" ++ zmodload -F zsh/stat b:zstat 2> /dev/null ++ local _zshz_pfx _zshz_part _zshz_luid ++ for _zshz_part in ${(s:/:)_zshz_df}; do ++ [[ -n $_zshz_part ]] || continue ++ _zshz_pfx+="/$_zshz_part" ++ [[ -L $_zshz_pfx ]] || continue ++ # Without zsh/stat there is no way to tell whose link this is, so refuse ++ # it rather than guess: this path is privileged by definition. ++ _zshz_luid='' ++ (( ${+builtins[zstat]} )) && ++ _zshz_luid=$(zstat -L +uid "$_zshz_pfx" 2> /dev/null) ++ if [[ $_zshz_luid != 0 ]]; then ++ (( quiet )) || ++ print "ERROR: Zsh-z will not follow the symlink ${_zshz_pfx} on the way to its datafile while ZSHZ_OWNER is set." >&2 ++ return 1 ++ fi ++ done ++ fi + +- # If the datafile is a directory, print a warning and exit ++ # If the user specified a datafile, use that or default to ~/.z ++ # If the datafile is a symlink, it gets dereferenced (except under ++ # $ZSHZ_OWNER, refused just above). Canonicalized with ++ # _zshz_realpath rather than a bare `:A', which would segfault Zsh 4.3.11 ++ # on a $ZSHZ_DATA pointing into a missing top-level directory -- at every ++ # prompt, since this line runs in the backgrounded precmd add. ++ _zshz_realpath "${custom_datafile:-$HOME/.z}" ++ local datafile=$REPLY ++ # Clear REPLY as soon as it is captured: the matching machinery below ++ # relies on it staying empty until a common root or best match is put in ++ # it (_zshz_find_common_root only assigns REPLY when it finds a root), so ++ # a datafile path left in REPLY here would surface as a bogus match. ++ REPLY='' ++ ++ # If the datafile is a directory, print a warning and return + if [[ -d $datafile ]]; then +- print "ERROR: Zsh-z's datafile (${datafile}) is a directory." >&2 +- exit ++ (( quiet )) || ++ print "ERROR: Zsh-z's datafile (${datafile}) is a directory." >&2 ++ return 1 + fi + + # Make sure that the datafile exists before attempting to read it or lock it +- # for writing +- [[ -f $datafile ]] || { mkdir -p "${datafile:h}" && touch "$datafile" } ++ # for writing. Create it with 0600 permissions from the first instant (umask ++ # in a subshell) rather than chmodding it afterward: this creation runs ++ # before the lock is taken, and on Cygwin/MSYS2 a concurrent writer's rename ++ # passes through a window in which the datafile is unlinked or delete- ++ # pending, so any second syscall on the path (chmod) -- or even the creating ++ # open itself -- can fail spuriously. Append mode (>>) creates the file ++ # without truncating one that a concurrent writer has just renamed into ++ # place. The first attempt is silent; if the file still does not exist ++ # afterward (so no concurrent writer supplied it), retry loudly so that real ++ # failures (directory permissions, read-only filesystem) reach the user. ++ [[ -f $datafile ]] || { ++ mkdir -p "${datafile:h}" && ++ ( umask 077; : >> "$datafile" ) 2> /dev/null || ++ [[ -f $datafile ]] || ++ ( umask 077; : >> "$datafile" ) ++ # When $ZSHZ_OWNER is set (e.g. under `sudo -s'), hand the freshly created ++ # file off to that user immediately, so a query-only invocation can't leave ++ # behind a root-owned .z that the normal-user shell can't read. `-h' so a ++ # symlink that appeared since the check above is retitled itself rather ++ # than dereferenced onto its target. ++ local _owner=${ZSHZ_OWNER:-${_Z_OWNER}} ++ [[ -n $_owner ]] && ++ ${ZSHZ[CHOWN]} -h "${_owner}:$(id -ng "${_owner}")" "$datafile" ++ } ++ ++ # If the datafile still does not exist, the loud retry above has already ++ # said why; nothing below -- reading, locking, writing -- can succeed ++ # without it, and each failure would add its own noise. Bailing out here ++ # matters most on Zsh 4.3.11, where the failed `$(< $datafile)' reads ++ # below are fatal to a non-interactive shell. ++ [[ -f $datafile ]] || return 1 + + # Bail if we don't own the datafile and $ZSHZ_OWNER is not set + [[ -z ${ZSHZ_OWNER:-${_Z_OWNER}} && -f $datafile && ! -O $datafile ]] && + return + +- # Load the datafile into an array and parse it +- lines=( ${(f)"$(< $datafile)"} ) +- # Discard entries that are incomplete or incorrectly formatted +- lines=( ${(M)lines:#/*\|[[:digit:]]##[.,]#[[:digit:]]#\|[[:digit:]]##} ) +- + ############################################################ + # Add a path to or remove one from the datafile + # + # Globals: + # ZSHZ + # ZSHZ_EXCLUDE_DIRS ++ # ZSHZ_LOCK_TIMEOUT ++ # ZSHZ_NO_RESOLVE_SYMLINKS + # ZSHZ_OWNER + # + # Arguments: +@@ -206,17 +417,21 @@ zshz() { + # $2 The path to add + ############################################################ + _zshz_add_or_remove_path() { +- local action=${1} ++ local action=$1 + shift + + if [[ $action == '--add' ]]; then + +- # TODO: The following tasks are now handled by _agkozak_precmd. Dead code? ++ # These $HOME / $ZSHZ_EXCLUDE_DIRS guards mirror the ones in ++ # _zshz_precmd, but they are not redundant: precmd filters $PWD as an ++ # early-out (skip the background fork), whereas --add is now a public ++ # entry point and must enforce the same policies as the precmd function. ++ # Keep both in sync. + + # Don't add $HOME + [[ $* == $HOME ]] && return + +- # Don't track directory trees excluded in ZSHZ_EXCLUDE_DIRS ++ # Don't track directory trees excluded in $ZSHZ_EXCLUDE_DIRS + local exclude + for exclude in ${(@)ZSHZ_EXCLUDE_DIRS:-${(@)_Z_EXCLUDE_DIRS}}; do + case $* in +@@ -225,96 +440,381 @@ zshz() { + done + fi + +- # A temporary file that gets copied over the datafile if all goes well +- local tempfile="${datafile}.${RANDOM}" +- +- # See https://github.com/rupa/z/pull/199/commits/ed6eeed9b70d27c1582e3dd050e72ebfe246341c +- if (( ZSHZ[USE_FLOCK] )); then +- +- local lockfd +- +- # Grab exclusive lock (released when function exits) +- zsystem flock -f lockfd "$datafile" 2> /dev/null || return ++ # Resolve the directory to be removed, and confirm a full-database wipe, ++ # *before* taking the lock. Both are independent of the datafile, and the ++ # confirmation is interactive: holding the lock across a `read -q' the user ++ # might walk away from would make concurrent writers in other shells time ++ # out on ZSHZ_LOCK_TIMEOUT and silently drop their adds while the prompt ++ # sits open. A lock should wrap the read-modify-write, never a question. ++ local xdir # Directory to be removed ++ if [[ $action == '--remove' ]]; then ++ # The target is canonicalized without any existence test: an entry ++ # whose directory has since been deleted is exactly the one a user most ++ # wants out of the database. _zshz_realpath resolves a missing path the ++ # way `:A' resolves one -- and, unlike a bare `:A', cannot segfault Zsh ++ # 4.3.11 on a path whose top-level component is gone. (The old ++ # `[[ -d ${...:A} ]]' guard offered no protection there: the `:A' ++ # expands, and crashes, before `-d' ever sees it.) ++ if (( ${ZSHZ_NO_RESOLVE_SYMLINKS:-${_Z_NO_RESOLVE_SYMLINKS}} )); then ++ xdir=${${*:-${PWD}}:a} ++ else ++ _zshz_realpath "${*:-${PWD}}" ++ xdir=$REPLY ++ fi + ++ # Both branches above yield a non-empty absolute path, and that ++ # matters: under `-R' an empty $xdir would collapse the subtree filter ++ # below into `${lines_to_keep:#/**}', which matches every line in the ++ # datafile and erases the lot -- silently, since the whole-database ++ # confirmation just below tests for `/' rather than for emptiness. Keep ++ # this guard in case a future change lets an empty resolution through. ++ [[ -n $xdir ]] || return 1 ++ ++ if (( ${+opts[-R]} )) && [[ $xdir == '/' ]]; then ++ if ! read -q "?Delete entire Zsh-z database? "; then ++ print && return 1 ++ fi ++ fi + fi + +- integer tmpfd +- case $action in +- --add) +- exec {tmpfd}>|"$tempfile" # Open up tempfile for writing +- _zshz_update_datafile $tmpfd "$*" +- local ret=$? +- ;; +- --remove) +- local xdir # Directory to be removed +- +- if (( ${ZSHZ_NO_RESOLVE_SYMLINKS:-${_Z_NO_RESOLVE_SYMLINKS}} )); then +- [[ -d ${${*:-${PWD}}:a} ]] && xdir=${${*:-${PWD}}:a} +- else +- [[ -d ${${*:-${PWD}}:A} ]] && xdir=${${*:-${PWD}}:A} ++ # A temporary file that gets copied over the datafile if all goes well ++ local tempfile="${datafile}.${RANDOM}" lockfile="${datafile}.lock" ++ integer lockfd=0 ++ # The no-flock fallback's lock. Deliberately a *different* name from ++ # $lockfile: a plain file left behind by a flock-capable Zsh would make ++ # `mkdir' fail forever on the same path, deadlocking every later write. ++ local lockdir="${datafile}.lock.d" ++ integer lockdir_held=0 ++ ++ { ++ # Using zsystem flock ++ if (( ZSHZ[USE_FLOCK] )); then ++ ++ # Obtain an exclusive lock on the lockfile. ++ # ++ # Locking the datafile directly would not actually serialize concurrent ++ # writers, since the datafile gets replaced by mv and each new datafile ++ # has a new inode -- so a separate, stable lockfile is needed. ++ # ++ # Bound the lock acquisition (default 1s, override with ZSHZ_LOCK_TIMEOUT) ++ # so a stuck holder can't stall the backgrounded precmd add or freeze a ++ # user's foreground `z --add' / `z -x'. Once the holder dies, the kernel ++ # frees the lock and the next add succeeds automatically -- no manual ++ # `rm ~/.z.lock' needed. ++ # ++ # On timeout we return silently and on purpose: the precmd add is ++ # best-effort and runs backgrounded (`&!'), so there is nowhere useful ++ # to report to -- a message would land on the terminal asynchronously, ++ # mid-keystroke, possibly every prompt. To diagnose a database that has ++ # stopped updating, run a foreground `z --add .' and check `$?': a ++ # nonzero status means the write did not happen -- 2 is a lock- ++ # acquisition timeout (contention, or a raised ZSHZ_LOCK_TIMEOUT is ++ # still too low), 1 is a permissions or ownership problem (e.g. a stale ++ # root-owned lockfile left by an earlier `sudo -s' session, or a ++ # symlinked lockfile refused under $ZSHZ_OWNER). ++ # Create the lockfile 0600-from-birth and silently (umask in a ++ # subshell), mirroring the datafile creation above rather than a bare ++ # `touch' under the ambient umask with unsuppressed stderr. zsystem ++ # flock opens the lockfile O_RDWR, so under `sudo -s' with $ZSHZ_OWNER ++ # the unprivileged user must be able to open it: hand it off at ++ # creation, not only after a successful write -- a timed-out or failed ++ # first write by root would skip the post-write chown and leave a ++ # root-owned lockfile, turning every later user --add / -x into a ++ # silently-swallowed EACCES no-op. The lockfile is deliberately never ++ # removed: unlinking one a waiter has already opened reintroduces the ++ # two-inodes race the stable lockfile exists to prevent. ++ # Under $ZSHZ_OWNER all of this runs with root's authority on a path the ++ # unprivileged owner controls, and every step follows a symlink: `-f' ++ # tests the target, `>>' creates a dangling one, and flock opens it. ++ # $datafile survives a planted link only because the `mv' below replaces ++ # it outright; the lockfile is deliberately never removed, so a symlink ++ # here would persist and be acted on at every subsequent write. Refuse. ++ local _lock_owner=${ZSHZ_OWNER:-${_Z_OWNER}} ++ [[ -n $_lock_owner && -L $lockfile ]] && return 1 ++ if [[ ! -f $lockfile ]]; then ++ ( umask 077; : >> "$lockfile" ) 2> /dev/null ++ [[ -n $_lock_owner ]] && ++ ${ZSHZ[CHOWN]} -h "${_lock_owner}:$(id -ng "${_lock_owner}")" "$lockfile" + fi ++ zsystem flock -t ${ZSHZ_LOCK_TIMEOUT:-1} -f lockfd "$lockfile" 2> /dev/null || return ++ ++ else + +- local -a lines_to_keep +- if (( ${+opts[-R]} )); then +- # Prompt user before deleting entire database +- if [[ $xdir == '/' ]] && ! read -q "?Delete entire Zsh-z database? "; then +- print && return 1 ++ # No `zsystem flock' here. MobaXterm's cut-down Cygwin is the case that ++ # matters -- it ships no `zsh/system' at all -- and until now this path ++ # wrote with nothing serializing it: every writer read its own snapshot ++ # and the last `mv' won. Measured on MobaXterm, an entry added by one of ++ # four concurrent writers went missing in 7 runs out of 10. ++ # ++ # `mkdir' is the portable atomic primitive: it succeeds for exactly one ++ # caller and fails for the rest, with no module behind it. What it does ++ # not give us is the kernel's release-on-death, which is the whole ++ # reason `flock' is preferred where it exists -- so a holder that dies ++ # would wedge every later write. Hence the staleness sweep below. ++ # ++ # Failure to acquire returns 2, the same status the flock branch's ++ # timeout produces and the one the README documents for contention. ++ integer _zshz_deadline=$(( EPOCHSECONDS + ${ZSHZ_LOCK_TIMEOUT:-1} )) ++ local -a _zshz_stale ++ while :; do ++ if mkdir "$lockdir" 2> /dev/null; then ++ lockdir_held=1 ++ break + fi +- # All of the lines that don't match the directory to be deleted +- lines_to_keep=( ${lines:#${xdir}\|*} ) +- # Or its subdirectories +- lines_to_keep=( ${lines_to_keep:#${xdir%/}/**} ) +- else +- # All of the lines that don't match the directory to be deleted +- lines_to_keep=( ${lines:#${xdir}\|*} ) +- fi +- if [[ $lines != "$lines_to_keep" ]]; then +- lines=( $lines_to_keep ) +- else +- return 1 # The $PWD isn't in the datafile +- fi +- exec {tmpfd}>|"$tempfile" # Open up tempfile for writing +- print -u $tmpfd -l -- $lines +- local ret=$? +- ;; +- esac ++ # Break a lock nobody can still be holding. A write is a matter of ++ # milliseconds, so a lock directory older than 30 seconds means its ++ # owner died without releasing it. `mkdir' stamps the mtime at ++ # creation and no holder touches it afterwards, so the age is the ++ # hold time. `$lockdir' expands literally here -- only the qualifier ++ # is glob syntax -- so a datafile path containing `[' or `*' is safe. ++ _zshz_stale=( ${lockdir}(Nms+30) ) ++ if (( ${#_zshz_stale} )); then ++ rmdir "$lockdir" 2> /dev/null && continue ++ fi ++ (( EPOCHSECONDS >= _zshz_deadline )) && return 2 ++ # No `zselect' on the platforms that land here, so this costs a fork. ++ # It is the slow path already, and spinning would be worse. ++ sleep 0.05 2> /dev/null || : ++ done + +- if (( tmpfd != 0 )); then +- # Close tempfile +- exec {tmpfd}>&- +- fi ++ fi + +- if (( ret != 0 )); then +- # Avoid clobbering the datafile if the write to tempfile failed +- ${ZSHZ[RM]} -f "$tempfile" +- return $ret +- fi ++ # Read the datafile only after obtaining the lock, so concurrent --add ++ # calls don't all act on the same stale snapshot. ++ lines=( ${(f)"$(< $datafile)"} ) ++ # Discard entries that are incomplete or incorrectly formatted ++ lines=( ${(M)lines:#/*\|[[:digit:]]##[.,]#[[:digit:]]#\|[[:digit:]]##} ) ++ ++ # Hold the fd in an *unset* scalar, not `integer tmpfd' (which seeds it ++ # with 0). On some Zsh builds, `exec {tmpfd}>|...' refuses to clobber a ++ # parameter already holding a number that names an open fd -- and 0 is ++ # stdin, always open -- yielding "can't clobber parameter tmpfd ++ # containing file descriptor 0". An empty scalar isn't a valid fd, so ++ # the guard never fires. See https://github.com/agkozak/zsh-z/issues/81 ++ local tmpfd ++ case $action in ++ --add) ++ # When zf_chmod isn't available (Zsh 4.3.11), avoid the ++ # ~900us fork+execve of external /usr/bin/chmod on every ++ # write. Create the tempfile with mode 0600 from the start ++ # via `umask 077' inside a subshell -- the umask change is ++ # contained to the forked child process and the OS prevents ++ # it from leaking back to the parent. Subshell fork without ++ # exec is ~50us, ~18x cheaper than the chmod fallback. ++ if [[ ${ZSHZ[CHMOD]} == 'zf_chmod' ]]; then ++ exec {tmpfd}>|"$tempfile" # Open up tempfile for writing ++ # Fail closed. The tempfile is born with the ambient umask (0666 ++ # under `umask 000'), and it is this inode -- not the datafile's -- ++ # that the rename below publishes, so a chmod whose failure went ++ # unnoticed would replace a 0600 datafile with a world-readable one ++ # and still report success. Nothing has been written yet, so ++ # there is no salvage: drop the tempfile and leave the database as ++ # it was. ++ if ! ${ZSHZ[CHMOD]} 600 "$tempfile"; then ++ exec {tmpfd}>&- ++ ${ZSHZ[RM]} -f "$tempfile" 2> /dev/null ++ return 1 ++ fi ++ _zshz_update_datafile $tmpfd "$*" ++ else ++ ( umask 077 ++ exec {tmpfd}>|"$tempfile" ++ _zshz_update_datafile $tmpfd "$*" ) ++ fi ++ local ret=$? ++ ;; ++ --remove) ++ # $xdir was resolved before the lock, and for `-xR /' the ++ # whole-database wipe was already confirmed there. ++ local -a lines_to_keep ++ if (( ${+opts[-R]} )); then ++ # All of the lines that don't match the directory to be deleted ++ lines_to_keep=( ${lines:#${xdir}\|*} ) ++ # Or its subdirectories ++ lines_to_keep=( ${lines_to_keep:#${xdir%/}/**} ) ++ else ++ # All of the lines that don't match the directory to be deleted ++ lines_to_keep=( ${lines:#${xdir}\|*} ) ++ fi ++ if [[ $lines != "$lines_to_keep" ]]; then ++ lines=( $lines_to_keep ) ++ else ++ return 1 # The $PWD isn't in the datafile ++ fi ++ # Same umask-subshell pattern as --add: avoid the external ++ # chmod when zf_chmod isn't available. ++ if [[ ${ZSHZ[CHMOD]} == 'zf_chmod' ]]; then ++ exec {tmpfd}>|"$tempfile" # Open up tempfile for writing ++ # Fail closed, exactly as on the --add path above. ++ if ! ${ZSHZ[CHMOD]} 600 "$tempfile"; then ++ exec {tmpfd}>&- ++ ${ZSHZ[RM]} -f "$tempfile" 2> /dev/null ++ return 1 ++ fi ++ # `-r': $lines are verbatim on-disk lines (the datafile stores ++ # literal paths), so they must be written back unchanged. Without ++ # `-r', print would collapse an escape -- e.g. a literal `\t' in a ++ # path into a tab -- silently corrupting bystander entries. ++ print -u $tmpfd -rl -- $lines ++ else ++ ( umask 077; print -rl -- $lines >| "$tempfile" ) ++ fi ++ local ret=$? ++ ;; ++ esac + +- local owner +- owner=${ZSHZ_OWNER:-${_Z_OWNER}} ++ if [[ -n $tmpfd ]]; then ++ # Close tempfile ++ exec {tmpfd}>&- ++ fi + +- if (( ZSHZ[USE_FLOCK] )); then +- # An unusual case: if inside Docker container where datafile could be bind +- # mounted +- if [[ -f '/.dockerenv' || ( -r '/proc/1/cgroup' && "$(< '/proc/1/cgroup')" == *docker* ) ]]; then +- print "$(< "$tempfile")" > "$datafile" 2> /dev/null ++ if (( ret != 0 )); then ++ # Avoid clobbering the datafile if the write to tempfile failed + ${ZSHZ[RM]} -f "$tempfile" +- # All other cases +- else +- ${ZSHZ[MV]} "$tempfile" "$datafile" 2> /dev/null || +- ${ZSHZ[RM]} -f "$tempfile" ++ return $ret + fi + +- if [[ -n $owner ]]; then +- ${ZSHZ[CHOWN]} ${owner}:"$(id -ng ${owner})" "$datafile" +- fi +- else +- if [[ -n $owner ]]; then +- ${ZSHZ[CHOWN]} "${owner}":"$(id -ng "${owner}")" "$tempfile" ++ integer write_ret chown_ret mv_attempts ++ local owner ++ owner=${ZSHZ_OWNER:-${_Z_OWNER}} ++ ++ if (( ZSHZ[USE_FLOCK] )); then ++ # An unusual case: if inside Docker container where datafile could be bind ++ # mounted ++ if [[ -f '/.dockerenv' || ( -r '/proc/1/cgroup' && "$(< '/proc/1/cgroup')" == *docker* ) ]]; then ++ # Secure the datafile *before* its contents land. This branch writes ++ # in place instead of renaming an already-0600 tempfile over the ++ # path, so asserting the mode afterwards -- as this did -- leaves a ++ # bind-mounted datafile that arrived permissive readable for the ++ # length of the write, and leaves it readable for good if the chmod ++ # fails and nothing checks. The mode carries across the truncating ++ # write below, which reuses this same inode. ++ if ! ${ZSHZ[CHMOD]} 600 "$datafile" 2> /dev/null; then ++ ${ZSHZ[RM]} -f "$tempfile" 2> /dev/null ++ return 1 ++ fi ++ # This is the one write path where a symlink at $datafile redirects ++ # real database content: the sibling branch renames a finished ++ # tempfile over the path, and a rename *replaces* a link rather than ++ # writing through it, while `>|' follows one. Under $ZSHZ_OWNER that ++ # content goes out with root's authority to a path an unprivileged ++ # owner controls, so a `-L' test ahead of the write is not enough -- ++ # the path can be swapped in between. ++ # ++ # `sysopen -o nofollow' settles it atomically, at open time, and the ++ # write goes through that descriptor. If it is unavailable (Zsh ++ # 4.3.11 has `zsystem flock' but no `sysopen' at all, and O_NOFOLLOW ++ # is not universal) or it refuses the open, the privileged write is ++ # refused rather than retried by a following one: this degrades to ++ # failing closed, never to writing unsafely. Without an owner set no ++ # privilege is crossed and the plain redirection stands. ++ # ++ # `chmod' above stays path-based -- Zsh has no `fchmod' -- so a swap ++ # can still misdirect it. Setting the mode on the wrong file is a far ++ # smaller matter than writing the database into it, and the write is ++ # what this closes. ++ local _zshz_dfd ++ if [[ -n $owner ]]; then ++ if (( ${+builtins[sysopen]} )) && ++ sysopen -o trunc,nofollow -w -u _zshz_dfd "$datafile" 2> /dev/null ++ then ++ print -u $_zshz_dfd -r -- "$(< "$tempfile")" 2> /dev/null ++ write_ret=$? ++ exec {_zshz_dfd}>&- ++ else ++ ${ZSHZ[RM]} -f "$tempfile" 2> /dev/null ++ return 1 ++ fi ++ else ++ # `-r': re-emit the tempfile's already-literal contents byte-for-byte. ++ print -r -- "$(< "$tempfile")" >| "$datafile" 2> /dev/null ++ write_ret=$? ++ fi ++ ${ZSHZ[RM]} -f "$tempfile" 2> /dev/null ++ # All other cases ++ else ++ # Retry a rename that a Windows sharing violation turned away; see ++ # the ZSHZ[MV_RETRIES] comment at the top of this file. Off Windows ++ # this loop makes the same single attempt it always has. Retrying is ++ # safe here: the rename happens under the lock, so no other writer ++ # can slip in between attempts. ++ while :; do ++ if ${ZSHZ[MV]} "$tempfile" "$datafile" 2> /dev/null; then ++ write_ret=0 ++ else ++ write_ret=$? ++ fi ++ (( write_ret == 0 )) && break ++ (( mv_attempts++ >= ${ZSHZ[MV_RETRIES]:-0} )) && break ++ if (( ${+ZSHZ[MV_RETRY_DELAY]} )); then ++ zselect -t ${ZSHZ[MV_RETRY_DELAY]} || : ++ fi ++ done ++ (( write_ret != 0 )) && ${ZSHZ[RM]} -f "$tempfile" 2> /dev/null ++ fi ++ # Preserve the write failure itself; best-effort tempfile cleanup must not ++ # turn a failed persist into a successful return. ++ (( write_ret == 0 )) || return $write_ret ++ ++ if [[ -n $owner ]]; then ++ # Chown the lockfile alongside the datafile: zsystem flock opens it ++ # O_RDWR, so if root creates it first under sudo -s, the unprivileged ++ # $ZSHZ_OWNER user's flock attempts would fail with EACCES (silently ++ # swallowed), turning --add and -x into no-ops. ++ # `-h' on both: the lockfile is never replaced, so a symlink planted ++ # there outlives any one write, and $datafile can be relinked in the ++ # window between the `mv' above and this line. Retitling the link ++ # itself -- which the owner already owns -- costs nothing, while ++ # dereferencing hands root's authority to whatever it names. ++ ${ZSHZ[CHOWN]} -h "${owner}:$(id -ng "${owner}")" "$datafile" "$lockfile" ++ chown_ret=$? ++ # Surface post-write chown failures too: the current write landed, but a ++ # wrong owner can break the next locked write. ++ (( chown_ret == 0 )) || return $chown_ret ++ fi ++ else ++ if [[ -n $owner ]]; then ++ ${ZSHZ[CHOWN]} -h "${owner}:$(id -ng "${owner}")" "$tempfile" ++ chown_ret=$? ++ if (( chown_ret != 0 )); then ++ # In the no-flock path, chown happens before the move, so clean up the ++ # tempfile and leave the live database untouched. ++ ${ZSHZ[RM]} -f "$tempfile" 2> /dev/null ++ return $chown_ret ++ fi ++ fi ++ # Same Windows sharing-violation retry as the flock branch above. This ++ # path is the one MobaXterm's cut-down Cygwin takes, and it has neither ++ # zsystem flock nor zsh/zselect, so the retries there run back to back. ++ while :; do ++ if ${ZSHZ[MV]} -f "$tempfile" "$datafile" 2> /dev/null; then ++ write_ret=0 ++ else ++ write_ret=$? ++ fi ++ (( write_ret == 0 )) && break ++ (( mv_attempts++ >= ${ZSHZ[MV_RETRIES]:-0} )) && break ++ if (( ${+ZSHZ[MV_RETRY_DELAY]} )); then ++ zselect -t ${ZSHZ[MV_RETRY_DELAY]} || : ++ fi ++ done ++ if (( write_ret != 0 )); then ++ ${ZSHZ[RM]} -f "$tempfile" 2> /dev/null ++ return $write_ret ++ fi + fi +- ${ZSHZ[MV]} -f "$tempfile" "$datafile" 2> /dev/null || +- ${ZSHZ[RM]} -f "$tempfile" +- fi ++ } always { ++ # zsystem flock -f opens a real fd; explicitly unlock it so repeated ++ # foreground `z --add' / `z -x' invocations in the interactive shell ++ # don't leak lock descriptors and stall peers. (A backgrounded precmd ++ # child releases its fd on exit regardless; this matters for the parent.) ++ (( lockfd != 0 )) && zsystem flock -u $lockfd 2> /dev/null ++ # Release the mkdir lock on every exit from the block above, including ++ # the early `return's -- unlike an fd, a directory outlives the process ++ # that made it, so a missed release here is a wedged database rather than ++ # a leaked descriptor. Only if this call is the one that took it. ++ (( lockdir_held )) && rmdir "$lockdir" 2> /dev/null ++ } + + # In order to make z -x work, we have to disable zsh-z's adding + # to the database until the user changes directory and the +@@ -346,31 +846,35 @@ zshz() { + # See https://github.com/rupa/z/issues/246 + local add_path=${(q)2} + +- local -a existing_paths + local now=$EPOCHSECONDS line dir + local path_field rank_field time_field count x ++ local -i keep + + rank[$add_path]=1 + time[$add_path]=$now + +- # Remove paths from database if they no longer exist + for line in $lines; do +- if [[ ! -d ${line%%\|*} ]]; then ++ path_field=${line%%\|*} ++ ++ # Filter non-existent paths (honoring ZSHZ_KEEP_DIRS) inline so ++ # we walk $lines once instead of twice. The `keep=1; break' also ++ # fixes a latent bug: the previous existence-check loop had no ++ # `break' after appending, so a non-existent path matching ++ # multiple ZSHZ_KEEP_DIRS patterns was processed more than once. ++ if [[ ! -d $path_field ]]; then ++ keep=0 + for dir in ${(@)ZSHZ_KEEP_DIRS}; do +- if [[ ${line%%\|*} == ${dir}/* || +- ${line%%\|*} == $dir || +- $dir == '/' ]]; then +- existing_paths+=( $line ) ++ if [[ $path_field == ${dir}/* || $path_field == $dir || $dir == '/' ]]; then ++ keep=1 ++ break + fi + done +- else +- existing_paths+=( $line ) ++ (( keep )) || continue + fi +- done +- lines=( $existing_paths ) + +- for line in $lines; do +- path_field=${(q)line%%\|*} ++ # Quote in place: assoc-array keys need shell-special chars ++ # backslash-escaped (rupa/z#246). ++ path_field=${(q)path_field} + rank_field=${${line%\|*}#*\|} + time_field=${line##*\|} + +@@ -378,8 +882,13 @@ zshz() { + (( rank_field < 1 )) && continue + + if [[ $path_field == $add_path ]]; then +- rank[$path_field]=$rank_field +- (( rank[$path_field]++ )) ++ # Compute the new rank with a scalar expression, not `(( rank[$key]++ ))'. ++ # The keys are `${(q)}'-quoted (rupa/z#246); a math-context subscript ++ # runs its key through the arithmetic lexer, which strips a backslash ++ # level and so misses any key containing `$ \ [ ] ( )' or a backtick -- ++ # incrementing a phantom raw-keyed entry and leaving the real one stuck. ++ # An assignment subscript expands the key literally, so it is safe. ++ rank[$path_field]=$(( rank_field + 1 )) + time[$path_field]=$now + else + rank[$path_field]=$rank_field +@@ -387,16 +896,33 @@ zshz() { + fi + (( count += rank_field )) + done ++ local -a out + if (( count > ${ZSHZ_MAX_SCORE:-${_Z_MAX_SCORE:-9000}} )); then + # Aging + for x in ${(k)rank}; do +- print -u $fd -- "$x|$(( 0.99 * rank[$x] ))|${time[$x]}" || return 1 ++ # `${rank[$x]}', not a bare `rank[$x]' math subscript: the keys are ++ # `${(q)}'-quoted (rupa/z#246), and a math-context subscript would run ++ # the key through the arithmetic lexer, stripping a backslash level and ++ # missing any key with `$ \ [ ] ( )' or a backtick -- yielding 0, which ++ # the `rank_field < 1' drop above then erases on the next write. The ++ # expansion substitutes the numeric value before the math parser runs. ++ out+=( "$x|$(( 0.99 * ${rank[$x]} ))|${time[$x]}" ) + done + else + for x in ${(k)rank}; do +- print -u $fd -- "$x|${rank[$x]}|${time[$x]}" || return 1 ++ out+=( "$x|${rank[$x]}|${time[$x]}" ) + done + fi ++ # Deliberately NO `-r' here, unlike every other datafile write. The keys in ++ # $out are `${(q)}'-quoted (assoc-array keys need shell-special chars ++ # backslash-escaped -- rupa/z#246), and a plain `print' strips exactly one ++ # backslash level back off, so what lands on disk is the literal path the ++ # rest of the code expects. Adding `-r' would store the still-quoted form ++ # (e.g. `/foo\ bar'), which the read path -- it does not unquote -- would ++ # then fail to match. The verbatim-passthrough writes in ++ # `_zshz_add_or_remove_path' DO use `-r' because their input is already ++ # literal; this one is not. ++ print -u $fd -l -- $out || return 1 + } + + ############################################################ +@@ -418,21 +944,29 @@ zshz() { + # Replace spaces in the search string with asterisks for globbing + 1=${1//[[:space:]]/*} + ++ # Hoist loop-invariants out of the per-line loop -- $1 and ++ # $ZSHZ_TRAILING_SLASH don't change inside the loop, so the ++ # lowercase comparison and the trailing-slash branch were pure ++ # waste when recomputed N times. `query_lower' lets the case- ++ # insensitive branch glob against a precompiled lowercase pattern. ++ local query_lower=${1:l} ++ local -i is_lowercase_query=0 ++ [[ $1 == $query_lower ]] && is_lowercase_query=1 ++ local -i trail=${ZSHZ_TRAILING_SLASH:-0} ++ + for line in $lines; do + + path_field=${line%%\|*} + + path_field_normalized=$path_field +- if (( ZSHZ_TRAILING_SLASH )); then +- path_field_normalized=${path_field%/}/ +- fi ++ (( trail )) && path_field_normalized=${path_field%/}/ + + # If the search string is all lowercase, the search will be case-insensitive +- if [[ $1 == "${1:l}" && ${path_field_normalized:l} == *${~1}* ]]; then +- print -- $path_field ++ if (( is_lowercase_query )) && [[ ${path_field_normalized:l} == *${~query_lower}* ]]; then ++ print -r -- $path_field + # Otherwise, case-sensitive + elif [[ $path_field_normalized == *${~1}* ]]; then +- print -- $path_field ++ print -r -- $path_field + fi + + done +@@ -440,62 +974,18 @@ zshz() { + # insensitively. + } + +- ############################################################ +- # `print' or `printf' to REPLY +- # +- # Variable assignment through command substitution, of the +- # form +- # +- # foo=$( bar ) +- # +- # requires forking a subshell; on Cygwin/MSYS2/WSL1 that can +- # be surprisingly slow. Zsh-z avoids doing that by printing +- # values to the variable REPLY. Since Zsh v5.3.0 that has +- # been possible with `print -v'; for earlier versions of the +- # shell, the values are placed on the editing buffer stack +- # and then `read' into REPLY. +- # +- # Globals: +- # ZSHZ +- # +- # Arguments: +- # Options and parameters for `print' +- ############################################################ +- _zshz_printv() { +- # NOTE: For a long time, ZSH's `print -v' had a tendency +- # to mangle multibyte strings: +- # +- # https://www.zsh.org/mla/workers/2020/msg00307.html +- # +- # The bug was fixed in late 2020: +- # +- # https://github.com/zsh-users/zsh/commit/b6ba74cd4eaec2b6cb515748cf1b74a19133d4a4#diff-32bbef18e126b837c87b06f11bfc61fafdaa0ed99fcb009ec53f4767e246b129 +- # +- # In order to support shells with the bug, we must use a form of `printf`, +- # which does not exhibit the undesired behavior. See +- # +- # https://www.zsh.org/mla/workers/2020/msg00308.html +- +- if (( ZSHZ[PRINTV] )); then +- builtin print -v REPLY -f %s $@ +- else +- builtin print -z $@ +- builtin read -rz REPLY +- fi +- } +- + ############################################################ + # If matches share a common root, find it, and put it in + # REPLY for _zshz_output to use. + # + # Arguments: +- # $1 Name of associative array of matches and ranks ++ # $@ Candidate paths + ############################################################ + _zshz_find_common_root() { + local -a common_matches + local x short + +- common_matches=( ${(@Pk)1} ) ++ common_matches=( "$@" ) + + for x in ${(@)common_matches}; do + if [[ -z $short ]] || (( $#x < $#short )) || [[ $x != ${short}/* ]]; then +@@ -509,7 +999,7 @@ zshz() { + [[ $x != $short* ]] && return + done + +- _zshz_printv -- $short ++ REPLY=$short + } + + ############################################################ +@@ -521,6 +1011,7 @@ zshz() { + # 3) Put a common root or best match into REPLY + # + # Globals: ++ # ZSHZ_TILDE + # ZSHZ_UNCOMMON + # + # Arguments: +@@ -532,66 +1023,110 @@ zshz() { + _zshz_output() { + + local match_array=$1 match=$2 format=$3 +- local common k x ++ local common x v + local -a descending_list output +- local -A output_matches +- +- output_matches=( ${(Pkv)match_array} ) + +- _zshz_find_common_root $match_array ++ _zshz_find_common_root ${(@Pk)match_array} + common=$REPLY ++ # Clear REPLY once the common root is captured: the caller reads REPLY as ++ # the jump target, so a value left over here would make `z -l ' ++ # change directory after listing. The default arm below overwrites REPLY ++ # deliberately; the completion and list arms must leave it empty. ++ REPLY='' ++ ++ # Iterate the caller's matches/imatches array as flat key-value ++ # pairs via ${(@Pkv)...} instead of copying into a local ++ # associative array. Avoids the hash-table allocation and K ++ # inserts that the copy required. ++ local -a kv ++ local -i i ++ kv=( ${(@Pkv)match_array} ) + + case $format in + + completion) +- for k in ${(@k)output_matches}; do +- _zshz_printv -f "%.2f|%s" ${output_matches[$k]} $k +- descending_list+=( ${(f)REPLY} ) +- REPLY='' ++ # Build "sortkey|path" rows, sort by the leading key descending, then ++ # strip the key+'|' prefix to keep just the paths (the key is never ++ # user-visible). The key MUST be an integer: `${(@On)}' numeric sort ++ # compares each run of digits on its own, so a raw float rank orders by ++ # its fractional digit-run rather than its value -- "100.5" would sort ++ # below "100.25" (5 < 25). Scale by 100 and drop the decimal so two ++ # digits of resolution survive (what the old `%.2f' rows preserved) as a ++ # single integer digit-run. (Negative `-t' ranks still sort by ++ # magnitude, since `n' ignores the sign -- unchanged from the `%.2f' ++ # rows, i.e. a pre-existing quirk, not introduced here.) ++ local sortkey ++ for ((i=1; i<=${#kv}; i+=2)); do ++ sortkey=$(( kv[i+1] * 100 )) ++ descending_list+=( "${sortkey%.*}|${kv[i]}" ) + done + descending_list=( ${${(@On)descending_list}#*\|} ) +- print -l $descending_list ++ print -rl -- $descending_list + ;; + + list) ++ # The bare `z -l' fast path (no query) inlines an equivalent ++ # formatting block straight on $lines to skip this pipeline -- ++ # keep the two list formatters in sync. + local path_to_display +- for x in ${(k)output_matches}; do +- if (( ${output_matches[$x]} )); then +- path_to_display=$x +- (( ZSHZ_TILDE )) && +- path_to_display=${path_to_display/#${HOME}/\~} +- _zshz_printv -f "%-10d %s\n" ${output_matches[$x]} $path_to_display +- output+=( ${(f)REPLY} ) +- REPLY='' +- fi ++ local -a displayed_paths ++ for ((i=1; i<=${#kv}; i+=2)); do ++ x=${kv[i]} v=${kv[i+1]} ++ (( v )) || continue ++ displayed_paths+=( $x ) ++ path_to_display=$x ++ (( ZSHZ_TILDE )) && ++ path_to_display=${path_to_display/#${HOME}/\~} ++ # Right-pad the integer rank to 10 chars, as `printf "%-10d %s\n"' ++ # used to, but in parameter expansion. The padding must be ++ # conditional: `%-10d' never shortened anything, but a bare ++ # `${(r:10:)}' *truncates* a rank longer than 10 characters -- an ++ # 11-character `-t' rank (sign + 10 digits, e.g. from a zeroed or ++ # hand-imported time field more than ~31.7 years old) or a frecency ++ # rank inflated by a raised $ZSHZ_MAX_SCORE would lose its last ++ # digits, garbling both the displayed figure and the numeric sort ++ # below. The `%.*' strip drops frecency's decimal tail ++ # ("30000.0" -> "30000") to match what `%-10d' produced. ++ v=${v%.*} ++ (( ${#v} < 10 )) && v=${(r:10:)v} ++ output+=( "$v $path_to_display" ) + done ++ # Recompute the common root over the entries that survived the rank ++ # filter above: $common, computed at the top of this function, ++ # covers *every* match -- including rank-0 entries hidden from the ++ # listing -- so it could name a root the visible entries do not ++ # share. The bare `z -l' fast path filters rank-0 entries before ++ # looking for a root, and the two formatters must produce identical ++ # output. (The jump arm below still uses the full-match root: what ++ # `z foo' jumps to is a separate question from what a listing ++ # displays.) ++ common='' ++ if (( $#displayed_paths )); then ++ _zshz_find_common_root $displayed_paths ++ common=$REPLY ++ # A listing must never leave a jump target in REPLY. ++ REPLY='' ++ fi + if [[ -n $common ]]; then + (( ZSHZ_TILDE )) && common=${common/#${HOME}/\~} + (( $#output > 1 )) && printf "%-10s %s\n" 'common:' $common + fi +- # -lt +- if (( $+opts[-t] )); then +- for x in ${(@On)output}; do +- print -- $x +- done +- # -lr +- elif (( $+opts[-r] )); then +- for x in ${(@on)output}; do +- print -- $x +- done +- # -l +- else +- for x in ${(@on)output}; do +- print $x +- done ++ if (( $#output )); then ++ # -lt: most-recent first (descending); -lr and default -l: ++ # ascending rank. ++ if (( $+opts[-t] )); then ++ print -rl -- ${(@On)output} ++ else ++ print -rl -- ${(@on)output} ++ fi + fi + ;; + + *) + if (( ! ZSHZ_UNCOMMON )) && [[ -n $common ]]; then +- _zshz_printv -- $common ++ REPLY=$common + else +- _zshz_printv -- ${(P)match} ++ REPLY=${(P)match} + fi + ;; + esac +@@ -606,63 +1141,85 @@ zshz() { + # ZSHZ + # ZSHZ_CASE + # ZSHZ_KEEP_DIRS +- # ZSHZ_OWNER ++ # ZSHZ_TRAILING_SLASH + # + # Arguments: +- # #1 Pattern to match ++ # $1 Pattern to match + # $2 Matching method (rank, time, or [default] frecency) + # $3 Output format (completion, list, or [default] store +- # in REPLY ++ # in REPLY) + ############################################################ + _zshz_find_matches() { + setopt LOCAL_OPTIONS NO_EXTENDED_GLOB + + local fnd=$1 method=$2 format=$3 + +- local -a existing_paths +- local line dir path_field rank_field time_field rank dx escaped_path_field ++ local line dir path_field rank_field time_field rank dx + local -A matches imatches + local best_match ibest_match hi_rank=-9999999999 ihi_rank=-9999999999 ++ local -i keep ++ ++ # Hoist loop-invariants. $fnd, $1, and $ZSHZ_TRAILING_SLASH don't ++ # change inside the per-line loop, so the space-to-glob ++ # substitution, the `${1:l} == $1' check, and the `:l' on $q were ++ # pure waste when recomputed N times. The `q_lower' precompute ++ # lets `${~q_lower}' replace `${~q:l}' in the case-insensitive ++ # branches: same expanded pattern, compiled once. ++ local q=${fnd//[[:space:]]/\*} ++ local q_lower=${q:l} ++ local -i is_lowercase_query=0 ++ [[ ${1:l} == $1 ]] && is_lowercase_query=1 ++ local -i trail=${ZSHZ_TRAILING_SLASH:-0} ++ local now=$EPOCHSECONDS ++ ++ # This flag is consumed by the ZSHZ_UNCOMMON trimming block, which must know ++ # whether the match it is about to trim was found case-insensitively. Clear ++ # it at the start of every search so a value left over from a previous call ++ # -- e.g. a tab-completion, which sets it but never runs the trimming block ++ # that would reset it -- can't steer this search into the wrong branch. The ++ # authoritative value is set below, from whichever match actually wins. ++ ZSHZ[CASE_INSENSITIVE]=0 + +- # Remove paths from database if they no longer exist + for line in $lines; do +- if [[ ! -d ${line%%\|*} ]]; then ++ path_field=${line%%\|*} ++ ++ # Filter non-existent paths (honoring ZSHZ_KEEP_DIRS) inline so we ++ # walk $lines once instead of twice. The `keep=1; break' inside the ++ # inner loop also fixes a latent bug: the previous existence-check ++ # loop had no `break' after appending, so a non-existent path that ++ # matched multiple ZSHZ_KEEP_DIRS patterns was processed more than ++ # once. ++ if [[ ! -d $path_field ]]; then ++ keep=0 + for dir in ${(@)ZSHZ_KEEP_DIRS}; do +- if [[ ${line%%\|*} == ${dir}/* || +- ${line%%\|*} == $dir || +- $dir == '/' ]]; then +- existing_paths+=( $line ) ++ if [[ $path_field == ${dir}/* || $path_field == $dir || $dir == '/' ]]; then ++ keep=1 ++ break + fi + done +- else +- existing_paths+=( $line ) ++ (( keep )) || continue + fi +- done +- lines=( $existing_paths ) + +- for line in $lines; do +- path_field=${line%%\|*} + rank_field=${${line%\|*}#*\|} + time_field=${line##*\|} + + case $method in + rank) rank=$rank_field ;; +- time) (( rank = time_field - EPOCHSECONDS )) ;; ++ time) (( rank = time_field - now )) ;; + *) +- # Frecency routine +- (( dx = EPOCHSECONDS - time_field )) ++ # Frecency routine: weight a path's stored frequency (rank_field) ++ # by how recently it was visited (dx seconds ago). 10000 scales ++ # the result into integer-comparable territory; the 3.75 / (...) ++ # term decays from 3 (just now) toward 0 as dx grows, so older ++ # paths lose rank. This is the canonical copy; the bare `z -l' ++ # fast path inlines the same formula -- keep the two in sync. ++ (( dx = now - time_field )) + rank=$(( 10000 * rank_field * (3.75/( (0.0001 * dx + 1) + 0.25)) )) + ;; + esac + +- # Use spaces as wildcards +- local q=${fnd//[[:space:]]/\*} +- +- # If $ZSHZ_TRAILING_SLASH is set, use path_field with a trailing slash for matching. + local path_field_normalized=$path_field +- if (( ZSHZ_TRAILING_SLASH )); then +- path_field_normalized=${path_field%/}/ +- fi ++ (( trail )) && path_field_normalized=${path_field%/}/ + + # If $ZSHZ_CASE is 'ignore', be case-insensitive. + # +@@ -671,33 +1228,32 @@ zshz() { + # + # Otherwise, the default behavior of Zsh-z is to match case-sensitively if + # possible, then to fall back on a case-insensitive match if possible. +- if [[ $ZSHZ_CASE == 'smart' && ${1:l} == $1 && +- ${path_field_normalized:l} == ${~q:l} ]]; then ++ # ++ # Track best_match / ibest_match directly from $rank in each branch so ++ # we never have to math-subscript matches[] / imatches[] -- the math ++ # parser interprets shell-special chars in associative-array keys as ++ # syntax (rupa/z#246), and the workaround used to be a seven-char ++ # escape pass on every line. Comparing the $rank scalar to the running ++ # max sidesteps the subscript entirely. ++ if [[ $ZSHZ_CASE == 'smart' ]] && (( is_lowercase_query )) && ++ [[ ${path_field_normalized:l} == ${~q_lower} ]]; then + imatches[$path_field]=$rank ++ if (( rank > ihi_rank )); then ++ ibest_match=$path_field ++ ihi_rank=$rank ++ fi + elif [[ $ZSHZ_CASE != 'ignore' && $path_field_normalized == ${~q} ]]; then + matches[$path_field]=$rank +- elif [[ $ZSHZ_CASE != 'smart' && ${path_field_normalized:l} == ${~q:l} ]]; then ++ if (( rank > hi_rank )); then ++ best_match=$path_field ++ hi_rank=$rank ++ fi ++ elif [[ $ZSHZ_CASE != 'smart' && ${path_field_normalized:l} == ${~q_lower} ]]; then + imatches[$path_field]=$rank +- fi +- +- # Escape characters that would cause "invalid subscript" errors +- # when accessing the associative array. +- escaped_path_field=${path_field//'\'/'\\'} +- escaped_path_field=${escaped_path_field//'`'/'\`'} +- escaped_path_field=${escaped_path_field//'('/'\('} +- escaped_path_field=${escaped_path_field//')'/'\)'} +- escaped_path_field=${escaped_path_field//'['/'\['} +- escaped_path_field=${escaped_path_field//']'/'\]'} +- +- if (( matches[$escaped_path_field] )) && +- (( matches[$escaped_path_field] > hi_rank )); then +- best_match=$path_field +- hi_rank=${matches[$escaped_path_field]} +- elif (( imatches[$escaped_path_field] )) && +- (( imatches[$escaped_path_field] > ihi_rank )); then +- ibest_match=$path_field +- ihi_rank=${imatches[$escaped_path_field]} +- ZSHZ[CASE_INSENSITIVE]=1 ++ if (( rank > ihi_rank )); then ++ ibest_match=$path_field ++ ihi_rank=$rank ++ fi + fi + done + +@@ -707,6 +1263,10 @@ zshz() { + if [[ -n $best_match ]]; then + _zshz_output matches best_match $format + elif [[ -n $ibest_match ]]; then ++ # The winning match is the case-insensitive one; tell the ZSHZ_UNCOMMON ++ # trimmer to count case-insensitively. A case-sensitive winner (the branch ++ # above) correctly leaves the flag at the 0 set at the top of the search. ++ ZSHZ[CASE_INSENSITIVE]=1 + _zshz_output imatches ibest_match $format + fi + } +@@ -736,6 +1296,17 @@ zshz() { + return 1 + fi + ++ # -r (rank) and -t (recent) name different, mutually exclusive sort keys, so ++ # asking for both is contradictory. Reject it rather than letting an arbitrary ++ # one win -- the options loop below visits ${(k)opts} in hash order, so a ++ # silent winner would not even be predictable. Skipped when --complete is set: ++ # the completion widget always passes it, an error must not reach the terminal ++ # mid-completion, and the sort order is merely cosmetic for a completion list. ++ if (( ${+opts[-r]} && ${+opts[-t]} && ! ${+opts[--complete]} )); then ++ print "${ZSHZ_CMD:-${_Z_CMD:-z}}: options -r and -t cannot be combined." >&2 ++ return 1 ++ fi ++ + local opt output_format method='frecency' fnd prefix req + + for opt in ${(k)opts}; do +@@ -760,6 +1331,9 @@ zshz() { + ;; + --complete) + if [[ -s $datafile && ${ZSHZ_COMPLETION:-frecent} == 'legacy' ]]; then ++ lines=( ${(f)"$(< $datafile)"} ) ++ # Discard entries that are incomplete or incorrectly formatted ++ lines=( ${(M)lines:#/*\|[[:digit:]]##[.,]#[[:digit:]]#\|[[:digit:]]##} ) + _zshz_legacy_complete "$1" + return + fi +@@ -771,7 +1345,10 @@ zshz() { + _zshz_usage + return + ;; +- -l) output_format='list' ;; ++ # --complete (completion mode) always wins over -l, independent of the ++ # order ${(k)opts} happens to visit them: completing `z -l ...' must still ++ # emit bare paths for compadd, never the rank-padded rows of a list. ++ -l) (( ${+opts[--complete]} )) || output_format='list' ;; + -r) method='rank' ;; + -t) method='time' ;; + -x) +@@ -785,6 +1362,12 @@ zshz() { + ;; + esac + done ++ ++ # Load the datafile into an array and parse it ++ lines=( ${(f)"$(< $datafile)"} ) ++ # Discard entries that are incomplete or incorrectly formatted ++ lines=( ${(M)lines:#/*\|[[:digit:]]##[.,]#[[:digit:]]#\|[[:digit:]]##} ) ++ + req="$*" + fnd="$prefix$*" + +@@ -816,13 +1399,17 @@ zshz() { + # If $ZSHZ_ECHO == 1, display paths as you jump to them. + # If it is also the case that $ZSHZ_TILDE == 1, display + # the home directory as a tilde. ++ # ++ # Globals: ++ # ZSHZ_ECHO ++ # ZSHZ_TILDE + ######################################################### + _zshz_echo() { + if (( ZSHZ_ECHO )); then + if (( ZSHZ_TILDE )); then +- print ${PWD/#${HOME}/\~} ++ print -r -- ${PWD/#${HOME}/\~} + else +- print $PWD ++ print -r -- $PWD + fi + fi + } +@@ -832,11 +1419,88 @@ zshz() { + [[ -d ${@: -1} ]] && zshz_cd ${@: -1} && _zshz_echo && return + fi + +- # With option -c, make sure query string matches beginning of matches; +- # otherwise look for matches anywhere in paths ++ # Fast path: bare `zshz -l' (no query, list format). Skip the ++ # `_zshz_find_matches' / `_zshz_output' pipeline -- there is nothing ++ # to match against, no `matches[]'/`imatches[]' to maintain, no ++ # case-mode branching, no `${(Pkv)...}' copy. Build the formatted ++ # output array directly, then sort and print. Mirrors the list arm ++ # of `_zshz_output' but operates straight on $lines. ++ if [[ $output_format == 'list' && -z $fnd ]]; then ++ local line path_field rank_field time_field rank dx path_to_display dir ++ local common now=$EPOCHSECONDS ++ local -a output paths ++ local -i keep ++ ++ for line in $lines; do ++ path_field=${line%%\|*} ++ ++ if [[ ! -d $path_field ]]; then ++ keep=0 ++ for dir in ${(@)ZSHZ_KEEP_DIRS}; do ++ if [[ $path_field == ${dir}/* || $path_field == $dir || $dir == '/' ]]; then ++ keep=1 ++ break ++ fi ++ done ++ (( keep )) || continue ++ fi ++ ++ rank_field=${${line%\|*}#*\|} ++ time_field=${line##*\|} ++ case $method in ++ rank) rank=$rank_field ;; ++ time) (( rank = time_field - now )) ;; ++ *) ++ # Frecency routine -- see _zshz_find_matches for the canonical ++ # copy and the constants' rationale; keep the two in sync. ++ (( dx = now - time_field )) ++ rank=$(( 10000 * rank_field * (3.75/( (0.0001 * dx + 1) + 0.25)) )) ++ ;; ++ esac ++ (( rank )) || continue ++ ++ paths+=( $path_field ) ++ path_to_display=$path_field ++ (( ZSHZ_TILDE )) && path_to_display=${path_to_display/#${HOME}/\~} ++ # Conditional padding, never a bare `${(r:10:)}' -- see the list arm ++ # of `_zshz_output' for why a rank must not be truncated. ++ rank=${rank%.*} ++ (( ${#rank} < 10 )) && rank=${(r:10:)rank} ++ output+=( "$rank $path_to_display" ) ++ done ++ ++ if (( $#paths )); then ++ _zshz_find_common_root $paths ++ common=$REPLY ++ REPLY= ++ fi ++ ++ if [[ -n $common ]]; then ++ (( ZSHZ_TILDE )) && common=${common/#${HOME}/\~} ++ (( $#output > 1 )) && printf "%-10s %s\n" 'common:' $common ++ fi + +- # zpm-zsh/colors has a global $c, so we'll avoid math expressions here +- if [[ ! -z ${(tP)opts[-c]} ]]; then ++ if (( $#output )); then ++ if (( $+opts[-t] )); then ++ print -rl -- ${(@On)output} ++ else ++ print -rl -- ${(@on)output} ++ fi ++ return 0 ++ fi ++ return 1 ++ fi ++ ++ # With option -c, make sure query string matches beginning of matches; ++ # otherwise look for matches anywhere in paths. ++ # ++ # The `$PWD != /' guard mirrors the one where the prefix is set, above. At the ++ # root every path is already under $PWD, so no "$PWD " prefix is prepended and ++ # $fnd stays the bare query -- which, anchored, can never match a path ++ # beginning with `/'. Without the guard, `z -c foo' from `/' matches nothing ++ # whatever the query. Anchoring is still right in the other prefix-less case ++ # ($* is an absolute path under $PWD): there the query is itself anchored. ++ if (( ${+opts[-c]} )) && [[ $PWD != '/' ]]; then + _zshz_find_matches "$fnd*" $method $output_format + else + _zshz_find_matches "*$fnd*" $method $output_format +@@ -845,7 +1509,12 @@ zshz() { + local ret2=$? + + local cd +- cd=$REPLY ++ # Only the default (jump/echo) format communicates a destination through ++ # REPLY; list and completion print their results directly and leave REPLY ++ # empty. Checking the format here is a second line of defense: even if a ++ # future edit to `_zshz_output' lets a stray REPLY escape again, a listing ++ # must never turn into a directory change. ++ [[ -z $output_format ]] && cd=$REPLY + + # New experimental "uncommon" behavior + # +@@ -866,6 +1535,10 @@ zshz() { + # Try dropping directory elements from the right; stop when it affects + # how many times the search pattern appears + until (( ( ${#cd:h} - ${#${${cd:h}//${~q}/}} ) != q_chars )); do ++ # ${cd:h} of `/' is `/', so without this guard the trim could spin ++ # forever once it reaches the root (e.g. `/' in the database with a ++ # pattern that matches zero characters there). ++ [[ ${cd:h} == $cd ]] && break + cd=${cd:h} + done + +@@ -873,6 +1546,9 @@ zshz() { + else + local q_chars=$(( ${#cd} - ${#${${cd:l}//${~${q:l}}/}} )) + until (( ( ${#cd:h} - ${#${${${cd:h}:l}//${~${q:l}}/}} ) != q_chars )); do ++ # See the case-sensitive branch: guard against ${cd:h} no longer ++ # changing once the trim reaches the root. ++ [[ ${cd:h} == $cd ]] && break + cd=${cd:h} + done + fi +@@ -884,7 +1560,7 @@ zshz() { + if (( ret2 == 0 )) && [[ -n $cd ]]; then + if (( $+opts[-e] )); then # echo + (( ZSHZ_TILDE )) && cd=${cd/#${HOME}/\~} +- print -- "$cd" ++ print -r -- "$cd" + else + # cd if possible; echo the new path if $ZSHZ_ECHO == 1 + [[ -d $cd ]] && zshz_cd "$cd" && _zshz_echo +@@ -924,13 +1600,37 @@ _zshz_precmd() { + esac + done + +- # It appears that forking a subshell is so slow in Windows that it is better +- # just to add the PWD to the datafile in the foreground +- if [[ $OSTYPE == (cygwin|msys) ]]; then +- zshz --add "$PWD" +- else +- (zshz --add "$PWD" &) +- fi ++ # Add PWD to the datafile. Background the write so the prompt doesn't wait on ++ # read + tempfile + rename + chown -- which is tens of ms per prompt on ++ # 9P-bridged or VHD-backed paths. Backgrounding is safe under develop's ++ # lock design: the `always { zsystem flock -u $lockfd }' block in ++ # _zshz_add_or_remove_path guarantees the parent never holds an open ++ # lockfd between precmd invocations (so a `&!' fork can't inherit one), ++ # and ZSHZ_LOCK_TIMEOUT (default 1s) bounds contention so a stuck holder ++ # can't pile up writers. `&!' is zsh background + disown: no wrapper ++ # subshell, no job-table entry, no "Done" line at the next prompt. ++ # ++ # Do not restore the old foreground carve-out for Cygwin/MSYS2. It was ++ # right when backgrounding meant a subshell plus a job (two forks) and ++ # writes were line-by-line; with one disowned fork and batched writes, ++ # measurement (June 2026, Cygwin zsh 5.8 and MSYS2 zsh 5.9) shows ~10-12ms ++ # at the prompt for `&!' vs. ~30ms for a foreground add at 300 datafile ++ # entries -- and ~300ms at 1,000 entries, since the foreground cost grows ++ # with the datafile while the fork cost stays flat. ++ # ++ # `2> /dev/null' is what actually enforces the "stay quiet at every prompt" ++ # rule that $_zshz_quiet_add describes. That marker can only gate Zsh-z's own ++ # `print's; it cannot reach the external and builtin commands further down the ++ # --add path -- `mkdir -p', `id -ng', ${ZSHZ[CHOWN]}, the deliberately loud ++ # datafile-creation retry, or Zsh's own redirection diagnostics -- and any of ++ # those can fail when $ZSHZ_DATA sits on an unwritable or unmounted directory, ++ # or when $ZSHZ_OWNER names a user `id' can't resolve. Suppressing at the fork ++ # covers every such site at once, including ones added later, whereas ++ # suppressing site by site has to be kept in sync forever. Nothing actionable ++ # is lost: a foreground `z --add .' still reports in full, which is exactly ++ # the diagnostic the lock comment above tells the user to run. ++ local _zshz_quiet_add=1 ++ zshz --add "$PWD" 2> /dev/null &! + + # See https://github.com/rupa/z/pull/247/commits/081406117ea42ccb8d159f7630cfc7658db054b6 + : $RANDOM +@@ -961,11 +1661,33 @@ add-zsh-hook chpwd _zshz_chpwd + + # Standardized $0 handling + # https://zdharma-continuum.github.io/Zsh-100-Commits-Club/Zsh-Plugin-Standard.html +-0="${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}" ++0="${${ZERO:-${0:#${ZSH_ARGZERO-}}}:-${(%):-%N}}" + 0="${${(M)0:#/*}:-$PWD/$0}" + +-(( ${fpath[(ie)${0:A:h}]} <= ${#fpath} )) || fpath=( "${0:A:h}" "${fpath[@]}" ) ++# Capture the plugin directory while $0 still names this file: inside the ++# unload function, $0 is the function name (FUNCTION_ARGZERO), which `:A' ++# would resolve against $PWD. ++ZSHZ[PLUGIN_DIR]=${0:A:h} + ++# Add the plugin directory to $fpath only when nothing else has already put it ++# there, and record having done so, so that unload can take back this entry ++# and leave a plugin manager's alone. ++# ++# The record is only ever set, never cleared: on a re-source the directory is ++# already present -- because this file added it the first time -- and clearing ++# the record then would strand the entry in $fpath at unload. `typeset -gA' ++# above preserves the value across that re-source. ++if (( ${fpath[(ie)${ZSHZ[PLUGIN_DIR]}]} > ${#fpath} )); then ++ fpath=( "${ZSHZ[PLUGIN_DIR]}" "${fpath[@]}" ) ++ # Record the path itself, not a boolean. $ZSHZ[PLUGIN_DIR] is rewritten by ++ # every source, so a flag would end up describing whichever directory was ++ # sourced last: re-sourcing from a second, manager-owned installation would ++ # make unload drop *that* entry and strand the one this plugin actually ++ # added. Newline-separated, since a path may contain spaces, and split with ++ # `${(f)...}' at unload. ++ ZSHZ[ADDED_FPATH]="${ZSHZ[ADDED_FPATH]:+${ZSHZ[ADDED_FPATH]} ++}${ZSHZ[PLUGIN_DIR]}" ++fi + + # Save the existing Tab binding so that the completion widget can invoke it, + # but being careful not to create a situation where the widget ends up calling +@@ -992,6 +1714,24 @@ _zshz_zle_completion_widget() { + + local cmd=${ZSHZ_CMD:-${_Z_CMD:-z}} + ++ # Ensure tab completion works under `setopt COMPLETE_ALIASES'. Under that ++ # option zsh looks up `_comps[$cmd]' verbatim rather than expanding the ++ # alias to `zshz' first; compinit's static `#compdef' tag in `_zshz' is ++ # parsed literally (no parameter expansion) and only covers the literal ++ # `zshz' command. Run once -- the guard short-circuits on subsequent Tabs. ++ # Record what was registered, so `zsh-z_plugin_unload' can take back exactly ++ # this entry and nothing else. Keyed on the effect rather than compdef's exit ++ # status: if the mapping did not land, there is nothing to take back. ++ if (( ! ${+_comps[$cmd]} )); then ++ compdef _zshz $cmd 2> /dev/null ++ # Append rather than overwrite. Re-sourcing with a changed $ZSHZ_CMD ++ # registers a second command while the first mapping is still live, and a ++ # single slot would forget the earlier one and strand it at unload. Space- ++ # separated, like $ZSHZ[FUNCTIONS], and split with `${=...}' there. ++ [[ ${_comps[$cmd]-} == '_zshz' ]] && ++ ZSHZ[COMPDEF]="${ZSHZ[COMPDEF]:+${ZSHZ[COMPDEF]} }$cmd" ++ fi ++ + # If a trailing space was added after an already-completed absolute path + # (e.g. `z /usr/local/bin '), a second Tab would otherwise re-trigger + # completion on an empty word and insert a duplicate. Bail out early. +@@ -1039,13 +1779,15 @@ fi + # zsh-z functions + ############################################################ + ZSHZ[FUNCTIONS]='_zshz_usage ++ _zshz_realpath + _zshz_add_or_remove_path + _zshz_update_datafile + _zshz_legacy_complete +- _zshz_printv + _zshz_find_common_root + _zshz_output + _zshz_find_matches ++ zshz_cd ++ _zshz_echo + zshz + _zshz_precmd + _zshz_chpwd +@@ -1095,9 +1837,49 @@ zsh-z_plugin_unload() { + (( ${+functions[$x]} )) && unfunction $x + done + +- unset ZSHZ ++ # The directory captured at source time -- $0 here is the function name, ++ # not the plugin file. Read it before ZSHZ is unset. ++ # ++ # Only when this plugin was the one that added it. A plugin manager that put ++ # the directory on $fpath owns that entry: taking it away would break ++ # autoloads for anything else living there and leave the manager believing ++ # its configuration is intact. And drop a single occurrence rather than ++ # filtering every match -- at most one of any duplicates can be ours. ++ # ++ # `(ie)', not `(i)': without the `e' the subscript treats the stored path as ++ # a *pattern*, so a plugin directory containing `[', `*' or `?' would not ++ # match itself and the entry would be left behind. The source-time lookup ++ # already uses `(ie)'; these two must agree. ++ local _zshz_dir ++ integer _zshz_fp ++ for _zshz_dir in ${(f)ZSHZ[ADDED_FPATH]-}; do ++ [[ -n $_zshz_dir ]] || continue ++ _zshz_fp=${fpath[(ie)$_zshz_dir]} ++ (( _zshz_fp <= ${#fpath} )) && fpath[$_zshz_fp]=() ++ done ++ ++ # Take back the completion mapping the widget installed on its first Tab. ++ # Without this the entry outlives the function it names -- `_zshz' is ++ # unfunctioned above and the plugin directory has just left $fpath, so a ++ # later completion on that command looks up something unloadable. ++ # ++ # Only this one entry. compinit's own registrations (`_comps[zshz]', from the ++ # static `#compdef' tag) are deliberately left in place: nothing re-runs ++ # compinit when the plugin is sourced again, so removing them would break ++ # completion for the literal `zshz' command until the user re-ran it by hand. ++ # This entry has no such problem -- the widget re-registers it on the next ++ # Tab after a reload. ++ # ++ # `$ZSHZ[COMPDEF]' is the ownership record: the registration above never ++ # overwrites an existing mapping, so one Zsh-z did not create must survive ++ # unload. Re-check the value too, in case it was repointed since. ++ local _zshz_compdef ++ for _zshz_compdef in ${=ZSHZ[COMPDEF]-}; do ++ [[ ${_comps[$_zshz_compdef]-} == '_zshz' ]] && ++ compdef -d "$_zshz_compdef" 2> /dev/null ++ done + +- fpath=( "${(@)fpath:#${0:A:h}}" ) ++ unset ZSHZ + + (( ${+aliases[${ZSHZ_CMD:-${_Z_CMD:-z}}]} )) && + unalias ${ZSHZ_CMD:-${_Z_CMD:-z}} diff --git a/tasks/ohmyzsh__ohmyzsh-13957/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-13957/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13957/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-13957/task.toml b/tasks/ohmyzsh__ohmyzsh-13957/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d383a1a500bf6a991da026fd96e4afcc6e49eea1 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13957/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-13957" +description = "chore(z): update to version 102fb780" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "b54a71977574cfcf659cc2f15a5e6422f17a8da7" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/13957" +source_access = "auto" +built_at = "2026-11-16T16:09:57.029872+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1df6e88bc627c9ef3b8b9d3ab1423f197dfa5253e0da306e82b3fd1a8600274b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-16T16:16:26Z" +diff_format = "unified" +context_files = [ + ".github/dependencies.yml", + "plugins/z/MANUAL.md", + "plugins/z/_z", + "plugins/z/z.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 1458 +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.960648+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:48c104d5c7ac1aa7732448d20b936b78e49d8b4fcac90871610c967eecb978fc" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-13957/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-13957/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13957/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-13957/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-13957/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b7ad072426c346f5448b561b54c863f3eb388400 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13957/tests/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** chore(z): update to version 102fb780 + +## Description + +## Description + +Update for **z plugin**: update to version . +Check out the [list of changes](https://github.com/agkozak/zsh-z/compare/agkozak:acd0e19...agkozak:102fb78). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b54a71977574`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13957/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-13957/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f1c2ed06dc365d040ac616213d5349045ab7c921 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13957/tests/oracle.patch @@ -0,0 +1,2027 @@ +diff --git a/.github/dependencies.yml b/.github/dependencies.yml +index b2440fa7..96d9991a 100644 +--- a/.github/dependencies.yml ++++ b/.github/dependencies.yml +@@ -46,9 +46,10 @@ dependencies: + plugins/z: + branch: master + repo: agkozak/zsh-z +- version: acd0e1984df350c189f8f9c4956ec586b6c73fca ++ version: 102fb78036ed76feedf623907483691777a1d510 + precopy: | + set -e ++ rm -r tests + test -e README.md && mv -f README.md MANUAL.md + postcopy: | + set -e +diff --git a/plugins/z/MANUAL.md b/plugins/z/MANUAL.md +index 420535b2..1c8a1d22 100644 +--- a/plugins/z/MANUAL.md ++++ b/plugins/z/MANUAL.md +@@ -2,20 +2,26 @@ + + [![MIT License](img/mit_license.svg)](https://opensource.org/licenses/MIT) + ![Zsh version 4.3.11 and higher](img/zsh_4.3.11_plus.svg) ++![Version](https://img.shields.io/github/v/release/agkozak/zsh-z) ++![Workflow Status](https://github.com/agkozak/zsh-z/actions/workflows/test.yml/badge.svg) + [![GitHub stars](https://img.shields.io/github/stars/agkozak/zsh-z.svg)](https://github.com/agkozak/zsh-z/stargazers) + + ![Zsh-z demo](img/demo.gif) + + Zsh-z is a command-line tool that allows you to jump quickly to directories that you have visited frequently or recently -- but most often a combination of the two (a concept known as ["frecency"](https://en.wikipedia.org/wiki/Frecency)). It works by keeping track of when you go to directories and how much time you spend in them. Based on this data, it predicts where you want to go when you type a partial string. For example, `z src` might take you to `~/src/zsh`. `z zsh` might also get you there, and `z c/z` might prove to be even more specific -- it all depends on your habits and how long you have been using Zsh-z to build up a database. After using Zsh-z for a little while, you will get to where you want to be by typing considerably less than you would need to if you were using `cd`. + +-Zsh-z is a native Zsh port of [`rupa/z`](https://github.com/rupa/z), a tool written for `bash` and Zsh that uses embedded `awk` scripts to do the heavy lifting. `rupa/z` was my most used command-line tool for a couple of years. I decided to translate it, `awk` parts and all, into pure Zsh script, to see if by eliminating calls to external tools (`awk`, `sort`, `date`, `sed`, `mv`, `rm`, and `chown`) and reducing forking through subshells I could make it faster. The performance increase is impressive, particularly on systems where forking is slow, such as Cygwin, MSYS2, and WSL. I have found that in those environments, switching directories using Zsh-z can be over 100% faster than it is using `rupa/z`. ++Zsh-z is a native Zsh port of [`rupa/z`](https://github.com/rupa/z), a tool written for `bash` and Zsh that uses embedded `awk` scripts to do the heavy lifting. `rupa/z` was my most used command-line tool for a couple of years. I decided to translate it, `awk` parts and all, into pure Zsh script, to see if by eliminating calls to external tools (`awk`, `sort`, `date`, `sed`, `mv`, `rm`, and `chown`) and reducing forking through subshells I could make it faster. The performance increase is impressive, particularly on systems where forking is slow, such as Cygwin, MSYS2, and WSL. + +-There is also a significant stability improvement. Race conditions have always been a problem with `rupa/z`, and users of that utility occasionally lose their `~/.z` databases. By having Zsh-z only use Zsh (`rupa/z` uses a hybrid shell code standard that works on `bash` as well), I have been able to implement a `zsh/system`-based file-locking mechanism similar to [the one @mafredri once proposed for `rupa/z`](https://github.com/rupa/z/pull/199). It is now nearly impossible to crash the database. ++There is also a significant stability improvement. Race conditions have always been a problem with `rupa/z`, and users of that utility occasionally lose their `~/.z` databases. By having Zsh-z only use Zsh (`rupa/z` uses a hybrid shell code standard that works on `bash` as well), I have been able to implement a `zsh/system`-based file-locking mechanism. It is now nearly impossible to crash the database. + +-There are other, smaller improvements which I document below in [Improvements and Fixes](#improvements-and-fixes). For instance, tab completions are now sorted by frecency by default rather than alphabetically (the latter behavior can be restored if you like it -- [see below](#settings)). ++There are other, smaller improvements which I document below in [Other Improvements to the Original Functionality of `rupa/z`](#other-improvements-to-the-original-functionality-of-rupaz). For instance, tab completions are now sorted by frecency by default rather than alphabetically (the latter behavior can be restored if you like it -- [see below](#settings)). + + Zsh-z is a drop-in replacement for `rupa/z` and will, by default, use the same database (`~/.z`, or whatever database file you specify), so you can go on using `rupa/z` when you launch `bash`. + ++> ### Zsh-z v2.0 ++> ++> **v2.0 is the most significant release in the project's history.** It is faster than ever at adding, searching, and listing on modern Zsh; it never makes your prompt wait on database writes -- on any platform; it hardens those writes against corruption and against prying eyes; and it makes tab completion "just work" even under `setopt COMPLETE_ALIASES`. See [**v2.0**](#v20) in the News below for the full rundown, and [Performance](#performance) for the benchmarks. ++ + ## Table of Contents + - [News](#news) + - [Installation](#installation) +@@ -23,16 +29,45 @@ Zsh-z is a drop-in replacement for `rupa/z` and will, by default, use the same d + - [Settings](#settings) + - [Case Sensitivity](#case-sensitivity) + - [`ZSHZ_UNCOMMON`](#zshz_uncommon) ++- [`ZSHZ_OWNER`](#zshz_owner) + - [Making `--add` work for you](#making---add-work-for-you) +-- [Other Improvements to the Original Functionality of `rupa/z`](#other-improvements-to-the-original-functionality-of-rupa-z) ++- [Performance](#performance) ++- [Other Improvements to the Original Functionality of `rupa/z`](#other-improvements-to-the-original-functionality-of-rupaz) + - [Migrating from Other Tools](#migrating-from-other-tools) + - [`COMPLETE_ALIASES`](#complete_aliases) + + ## News + ++### v2.0 (August 14, 2026) ++ ++Version **2.0** is a major step forward, and these are the changes most worth knowing about: ++ ++- **Zsh-z is even faster than before.** Version 2.0 builds on Zsh-z's past successes in optimizing adding to the datafile -- something it does at virtually every prompt -- by streamlining searching and listing, as well. See [Performance](#performance) for the numbers. ++- **Database writes never block your prompt** -- on any platform. The per-prompt `--add` has long run in the background on most systems, but Cygwin and MSYS2 did the write in the foreground, because backgrounding there cost a wrapper subshell plus a job. `--add` now runs as a single disowned job (`&!`) everywhere: one fork, no wrapper subshell, no job-control noise. On Cygwin and MSYS2 that turns a foreground write whose cost grows with your datafile (~30 ms at 300 entries, ~300 ms at 1,000) into a flat ~10-12 ms fork. Elsewhere it halves the forks per prompt. ++- **Safer, crash-resistant concurrent writes.** Writes are now guarded by a dedicated, stable lockfile using `zsh/system` file locking, with a bounded wait for lock acquisition (the new [`ZSHZ_LOCK_TIMEOUT`](#settings), default `1` second). Write errors are handled gracefully, and locks are always released even if a write is interrupted. On Cygwin and MSYS2 a write is also retried briefly if Windows refuses it: a virus scanner or the search indexer that opens the database in the instant between its being written and its being moved into place makes the move fail, which used to lose that one directory silently. Zsh-z now retries the move briefly. ++- **Your database file now has `600` permissions** -- readable and writable only by you -- so that other users on a shared system cannot read your directory history ([#92](https://github.com/agkozak/zsh-z/issues/92)). On Zsh 5+ this uses the in-process `zf_chmod` builtin; on Zsh 4.3.11 it uses a `umask`-in-a-subshell technique that avoids the fork-and-exec of an external `chmod`. ++- **`COMPLETE_ALIASES` works automatically in normal setups.** Tab completion no longer breaks when you have `setopt COMPLETE_ALIASES` enabled. Zsh-z registers the alias automatically on the first Tab press, so the manual `compdef` line that earlier versions required is no longer necessary. [See below](#complete_aliases). ++- **Fixed a `can't clobber parameter tmpfd` error on some Zsh builds.** On certain Zsh builds, every database write could fail with `can't clobber parameter tmpfd containing file descriptor 0`, leaving an error at each new prompt. The file descriptor used for the temporary database file is now held in an unset scalar rather than one seeded with `0`, so the write never trips Zsh's file-descriptor-clobber guard ([#81](https://github.com/agkozak/zsh-z/issues/81)). ++- **A misconfigured database file no longer closes your shell -- or nags you at every prompt.** When `ZSHZ_DATA` points at a directory, or names a file without a directory, Zsh-z now reports the problem and returns instead of calling `exit`. The per-prompt `--add` stays quiet about it, so you are told once, when you actually run `z`, rather than at every prompt ([#103](https://github.com/agkozak/zsh-z/issues/103); props @ahjota). ++- **`z -x` can now remove the entry for a directory that no longer exists -- and can no longer crash Zsh 4.3.11.** The removal target used to have to exist on disk, so a database entry whose directory had been deleted -- exactly the entry you most want gone -- could not be removed. `z -x /deleted/dir` (and `z -xR`) now canonicalizes the argument without requiring it to exist, resolving symlinks in as much of the path as is still present. The same change fixes a crash on Zsh 4.3.11, where an upstream bug makes `${x:A}` segfault when the top-level component of the path is missing: `z -x /gone/sub` -- or a `ZSHZ_DATA` pointing into a missing top-level directory -- could kill the shell there. ++- **More robust startup and operation.** A version check on an unsupported Zsh no longer risks exiting your interactive shell. ++ ++#### Smaller changes you may notice ++ ++None of these should need any action from you, but they are the things a v1 user is most likely to spot: ++ ++- **`-r` and `-t` can no longer be combined.** They name mutually exclusive sort orders -- rank versus recency -- so `z -rt foo` was always contradictory, and `-t` silently took precedence. It is now rejected with an error message instead of silently picking one. ++- **A lockfile appears next to your database.** Writes are serialized through `~/.z.lock` (or `$ZSHZ_DATA` plus `.lock`). It is created `600`, it stays empty, and it is deliberately never deleted -- removing a lockfile that another shell has already opened would reintroduce the very race it exists to prevent. Where `zsh/system` is missing and `zsystem flock` is therefore unavailable -- MobaXterm's cut-down Cygwin is the case in practice -- you will see a short-lived `~/.z.lock.d` **directory** instead, which is created and removed for each write. See [`ZSHZ_LOCK_TIMEOUT`](#settings) for how that fallback behaves. ++- **An existing database gets tightened to `600` on the next write.** If your `~/.z` predates this release and is `644`, the first write will re-mode it. This is the [#92](https://github.com/agkozak/zsh-z/issues/92) fix applied to databases you already have, not just newly created ones. Setting the mode is treated as part of the write rather than a courtesy afterwards: if it cannot be done, the write is abandoned and reports failure instead of publishing a database that anyone on the machine could read. ++ ++The dated entries below remain the historical record of changes leading up to v2.0. ++ +
      +- Here are the latest features and updates. ++ Here are the older features and updates. + ++- May 6, 2026 ++ + Zsh-z will now handle paths with dollar signs (`$`) in them. ++ + Workaround for Zsh emulating `sh`/`bash`/`ksh`. + - May 1, 2026 + + Various tab completion bugs resolved. + - April 27, 2026 +@@ -90,7 +125,7 @@ Zsh-z is a drop-in replacement for `rupa/z` and will, by default, use the same d + - February 15, 2021 + + Ranks are displayed the way `rupa/z` now displays them, i.e. as large integers. This should help Zsh-z to integrate with other tools. + - January 31, 2021 +- + Zsh-z is now efficient enough that, on MSYS2 and Cygwin, it is faster to run it in the foreground than it is to fork a subshell for it. ++ + Zsh-z is now efficient enough that, on MSYS2 and Cygwin, it is faster to run it in the foreground than it is to fork a subshell for it. (Behavior superseded in v2.0.) + + `_zshz_precmd` simply returns if `PWD` is `HOME` or in `ZSHZ_EXCLUDE_DIRS`, rather than waiting for `zshz` to do that. + - January 17, 2021 + + Made sure that the `PUSHD_IGNORE_DUPS` option is respected. +@@ -121,11 +156,11 @@ This plugin can be installed simply by putting the various files in a directory + + source /path/to/zsh-z.plugin.zsh + +-For tab completion to work, `_zshz` *must* be in the same directory as `zsh-z.plugin.zsh`, and you will want to have loaded `compinit`. The frameworks handle this themselves. If you are not using a framework, put ++Tab completion requires `compinit`. `_zshz` *must* also be in the same directory as `zsh-z.plugin.zsh`. The frameworks handle both of these requirements, but if you are not using a framework, put + + autoload -U compinit; compinit + +-in your `.zshrc` somewhere below where you source `zsh-z.plugin.zsh`. ++in your `.zshrc` somewhere below where you source `zsh-z.plugin.zsh` -- the plugin adds its directory to `fpath` at source time, and `compinit` needs to see it there in order to find `_zshz`. + + If you add + +@@ -195,7 +230,7 @@ Add a backslash to the end of the last line and add `'zsh-z'` to the list, e.g., + Then relaunch `zsh`. + + ### For [zcomet](https://github.com/agkozak/zcomet) users +- ++ + Simply add + + zcomet load agkozak/zsh-z +@@ -235,7 +270,7 @@ Add the line + + to your `.zshrc`. + +-Zsh-z supports `zinit`'s `unload` feature; just run `zinit unload agkozak/zsh-z` to restore the shell to its state before Zsh-z was loaded. ++Zsh-z supports `zinit`'s `unload` feature; just run `zinit unload agkozak/zsh-z` to restore the shell to its state before Zsh-z was loaded. It gives back only what it took: the `fpath` entry is removed only if Zsh-z was the one that added it, so a directory your plugin manager put there is left alone, and the Tab-completion mapping is dropped only while it still points at Zsh-z's own completer. + + ### For [Znap](https://github.com/marlonrichert/zsh-snap) users + +@@ -274,6 +309,7 @@ to install Zsh-z. + + Zsh-z has environment variables (they all begin with `ZSHZ_`) that change its behavior if you set them. You can also keep your old ones if you have been using `rupa/z` (whose environment variables begin with `_Z_`). + ++* `ZSHZ_CASE` can be `ignore`, for case-insensitive matching, or `smart`, for Vim-like `smartcase` matching; [see below](#case-sensitivity) (default: empty, i.e., a case-sensitive match is tried first, then a case-insensitive one) + * `ZSHZ_CMD` changes the command name (default: `z`) + * `ZSHZ_CD` specifies the default directory-changing command (default: `builtin cd`) + * `ZSHZ_COMPLETION` can be `'frecent'` (default) or `'legacy'`, depending on whether you want your completion results sorted according to frecency or simply sorted alphabetically +@@ -281,9 +317,10 @@ Zsh-z has environment variables (they all begin with `ZSHZ_`) that change its be + * `ZSHZ_ECHO` displays the new path name when changing directories (default: `0`) + * `ZSHZ_EXCLUDE_DIRS` is an array of directories to keep out of the database (default: empty) + * `ZSHZ_KEEP_DIRS` is an array of directories that should not be removed from the database, even if they are not currently available (useful when a drive is not always mounted) (default: empty) ++* `ZSHZ_LOCK_TIMEOUT` is the number of seconds to wait for the database lock before giving up on a write (default: `1`). Where `zsh/system` is unavailable and `zsystem flock` cannot be used -- MobaXterm's cut-down Cygwin, for instance -- Zsh-z serializes writes with an atomic `mkdir` on `~/.z.lock.d` instead, and this setting bounds the wait the same way. That fallback has no equivalent of the kernel releasing a lock when its holder dies, so a lock directory older than 30 seconds is treated as abandoned and cleared; a write takes milliseconds, so nothing legitimate is ever that old. A write that times out is dropped silently -- the automatic `precmd` add is best-effort -- so if the database seems to stop updating, the lock is probably contended: run `z --add .` by hand and check `$?`. A `2` is a lock-acquisition timeout, which confirms contention -- look for a stale process holding `~/.z.lock` (or a leftover `~/.z.lock.d` directory on the fallback path), or raise this setting. A `1` is something else entirely, usually a permissions or ownership problem, such as a root-owned `~/.z` or `~/.z.lock` left behind by an earlier `sudo -s` session. + * `ZSHZ_MAX_SCORE` is the maximum combined score the database entries can have before they begin to age and potentially drop out of the database (default: 9000) + * `ZSHZ_NO_RESOLVE_SYMLINKS` prevents symlink resolution (default: `0`) +-* `ZSHZ_OWNER` allows usage when in `sudo -s` mode (default: empty) ++* `ZSHZ_OWNER` is the username the database belongs to; set it to your own login name to keep `z` working in a root shell, such as under `sudo -E -s`; [see below](#zshz_owner) (default: empty) + * `ZSHZ_TILDE` displays the name of the `HOME` directory as a `~` (default: `0`) + * `ZSHZ_TRAILING_SLASH` makes it so that a search pattern ending in `/` can match the final element in a path; e.g., `z foo/` can match `/path/to/foo` (default: `0`) + * `ZSHZ_UNCOMMON` changes the logic used to calculate the directory jumped to; [see below](#zshz_uncommon) (default: `0`) +@@ -319,6 +356,12 @@ then there is no common prefix. In this case, `z code` will simply send you to t + + You may enable an alternate, experimental behavior by setting `ZSHZ_UNCOMMON=1`. If you do that, Zsh-z will not jump to a common prefix, even if one exists. Instead, it chooses the highest-ranking match -- but it drops any subdirectories that do not include the search term. So if you type `z bat` and `/home/me/code/bat` is the best match, that is exactly where you will end up. If, however, you had typed `z code` and the best match was also `/home/me/code/bat`, you would have ended up in `/home/me/code` (because `code` was what you had searched for). This feature is still in development, and feedback is welcome. + ++## `ZSHZ_OWNER` ++ ++If you are using `root` privileges while keeping your personal home directory as `HOME` (as is the case with `sudo -E -s`), conflicts with file ownership arise. You can resolve them by using `ZSHZ_OWNER`. If you set this variable to your username, Zsh-z will be able to use your personal datafile, restoring its proper ownership with every write. ++ ++Setting `ZSHZ_OWNER` makes one thing stricter, because a privileged shell is then writing to a path that an unprivileged user controls: Zsh-z follows a symlink on the way to the datafile -- the file itself, or any parent directory -- only if `root` owns the link, and reports an error instead of writing otherwise. Symlinked system directories, such as `/home` → `/usr/home` on the BSDs or `/var` → `/private/var` on macOS, belong to root and still resolve. With `ZSHZ_OWNER` unset none of this applies: a symlinked `~/.z` is followed exactly as before, so pointing it at synced storage keeps working. ++ + ## Making `--add` Work for You + + Zsh-z internally uses the `--add` option to add paths to its database. @zachriggle pointed out to me that users might want to use `--add` themselves, so I have altered it a little to make it more user-friendly. +@@ -331,9 +374,33 @@ A good example might involve a directory tree that has Git repositories within i + + (As a Zsh user, I tend to use `**` instead of `find`, but it is good to see how deep your directory trees go before doing that.) + ++## Performance ++ ++One of the goals of the rewrite that culminated in v2.0 was to make Zsh-z simultaneously more stable and faster. On modern Zsh, Zsh-z outpaces `rupa/z`'s `z.sh` at adding, searching, and listing. Representative figures (N = 200 database entries, medians of seven interleaved runs on a Core i7-12700 desktop under WSL2): ++ ++**Modern Zsh (5.9) -- Zsh-z vs. `rupa/z`:** ++ ++| Operation | `rupa/z` (`z.sh`) | Zsh-z | Winner | ++| --------- | ----------------- | ----------- | ----------------- | ++| `add` | 6.25 ms/op | 1.99 ms/op | **Zsh-z** ~3.14x | ++| `search` | 6.51 ms/op | 3.62 ms/op | **Zsh-z** ~1.80x | ++| `list` | 8.93 ms/op | 4.36 ms/op | **Zsh-z** ~2.05x | ++ ++**Zsh 4.3.11 (the oldest supported release) -- Zsh-z vs. `rupa/z`:** ++ ++| Operation | `rupa/z` (`z.sh`) | Zsh-z | Winner | ++| --------- | ----------------- | ----------- | ----------------- | ++| `add` | 5.00 ms/op | 2.92 ms/op | **Zsh-z** ~1.71x | ++| `search` | 4.93 ms/op | 4.47 ms/op | **Zsh-z** ~1.10x | ++| `list` | 7.92 ms/op | 6.08 ms/op | **Zsh-z** ~1.30x | ++ ++Removal is absent from these tables: in `rupa/z`, the per-prompt hook re-adds the current directory right after `z -x` removes it, so the two implementations' `-x` are not doing comparable work. ++ ++Relative to the previous generation of Zsh-z, the v2.0 read path is dramatically faster -- on modern Zsh, listing the whole database is about 2.4x faster and searching about 1.6x faster. ++ + ## Other Improvements to the Original Functionality of `rupa/z` + +-* `z -x` works, with the help of `chpwd_functions`. ++* `z -x` works: a directory you remove stays removed. + * Zsh-z is compatible with Solaris. + * Zsh-z uses the "new" `zshcompsys` completion system instead of the old `compctl` one. + * No error message is displayed when the database file has not yet been created. +@@ -355,12 +422,10 @@ If you are coming to Zsh-z (or even to the original `rupa/z`, for that matter) f + + ## `COMPLETE_ALIASES` + +-`z`, or any alternative you set up using `$ZSHZ_CMD` or `$_Z_CMD`, is an alias. `setopt COMPLETE_ALIASES` divorces the tab completion for aliases from the underlying commands they invoke, so if you enable `COMPLETE_ALIASES`, tab completion for Zsh-z will be broken. You can get it working again, however, by adding under +- +- setopt COMPLETE_ALIASES ++`z`, or any alternative you set up using `$ZSHZ_CMD` or `$_Z_CMD`, is an alias. `setopt COMPLETE_ALIASES` divorces the tab completion for aliases from the underlying commands they invoke, which historically broke Zsh-z's tab completion. Zsh-z now handles this automatically: the first Tab press registers the alias name with `_zshz` so completion works under `COMPLETE_ALIASES` without any extra setup. + +-the line ++That registration happens inside Zsh-z's own Tab widget. If a plugin loaded after Zsh-z replaces the Tab binding without invoking the previous widget, Zsh-z's widget never runs and the registration does not happen. Under `COMPLETE_ALIASES`, you would then have no completion for `z`. Once `compinit` has run, adding + + compdef _zshz ${ZSHZ_CMD:-${_Z_CMD:-z}} + +-That will re-bind `z` or the command of your choice to the underlying Zsh-z function. ++below `setopt COMPLETE_ALIASES` in your `.zshrc` fixes that, and it is harmless if the automatic registration has already run. +diff --git a/plugins/z/_z b/plugins/z/_z +index a109841d..09e70af4 100644 +--- a/plugins/z/_z ++++ b/plugins/z/_z +@@ -1,6 +1,6 @@ + #compdef zshz ${ZSHZ_CMD:-${_Z_CMD:-z}} + # +-# Zsh-z - jump around with Zsh - A native Zsh version of z without awk, sort, ++# Zsh-z - jump around with Zsh - A native Zsh version of rupa/z without awk, sort, + # date, or sed + # + # https://github.com/agkozak/zsh-z +@@ -24,11 +24,7 @@ + # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + # SOFTWARE. +-# +-# z (https://github.com/rupa/z) is copyright (c) 2009 rupa deadwyler and +-# licensed under the WTFPL license, Version 2.a +-# +-# shellcheck shell=ksh ++################################################################################ + + ############################################################ + # Zsh-z COMPLETIONS +diff --git a/plugins/z/z.plugin.zsh b/plugins/z/z.plugin.zsh +index 6df49822..d922fa77 100644 +--- a/plugins/z/z.plugin.zsh ++++ b/plugins/z/z.plugin.zsh +@@ -1,6 +1,6 @@ + ################################################################################ +-# Zsh-z - jump around with Zsh - A native Zsh version of z without awk, sort, +-# date, or sed ++# Zsh-z - jump around with Zsh - A native Zsh version of rupa/z without awk, ++# sort, date, or sed + # + # https://github.com/agkozak/zsh-z + # +@@ -24,9 +24,6 @@ + # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + # SOFTWARE. + # +-# z (https://github.com/rupa/z) is copyright (c) 2009 rupa deadwyler and +-# licensed under the WTFPL license, Version 2. +-# + # Zsh-z maintains a jump-list of the directories you actually use. + # + # INSTALL: +@@ -57,22 +54,45 @@ + # ZSHZ_COMPLETION -> completion method (default: 'frecent'; 'legacy' for + # alphabetic sorting) + # ZSHZ_DATA -> name of datafile (default: ~/.z) ++# ZSHZ_DEBUG -> if set, turn on debugging aids: WARN_CREATE_GLOBAL while the ++# command runs and per-function warnings (functions -W) at load time ++# (default: unset) ++# ZSHZ_ECHO -> if 1, print the directory name after jumping to it (default: 0) + # ZSHZ_EXCLUDE_DIRS -> array of directories to exclude from your database + # (default: empty) + # ZSHZ_KEEP_DIRS -> array of directories that should not be removed from the + # database, even if they are not currently available (default: empty) ++# ZSHZ_LOCK_TIMEOUT -> seconds to wait for the lockfile before giving up ++# (default: 1) + # ZSHZ_MAX_SCORE -> maximum combined score the database entries can have + # before beginning to age (default: 9000) + # ZSHZ_NO_RESOLVE_SYMLINKS -> '1' prevents symlink resolution + # ZSHZ_OWNER -> your username (if you want use Zsh-z while using sudo -s) ++# ZSHZ_TILDE -> if 1, display ~ in place of the full $HOME path in output ++# (default: 0) ++# ZSHZ_TRAILING_SLASH -> if 1, a query ending in / matches at the end of a ++# directory path (default: 0) + # ZSHZ_UNCOMMON -> if 1, do not jump to "common directories," but rather drop + # subdirectories based on what the search string was (default: 0) + ################################################################################ + +-autoload -U is-at-least ++# Minimalistic solution to allow this plugin to keep running under sh/bash/ksh ++# emulation while continuing to use Zsh-only syntax features. `emulate zsh -c' ++# evaluates its argument as code, so the script's own path -- `${(%):-%N}' -- ++# must be `${(q)}'-quoted; otherwise an install directory containing spaces or ++# other shell-special characters (common on Cygwin/MSYS2 and macOS, where a ++# home directory can be "C:\Users\John Smith" or "/Users/John Smith") would be ++# word-split and the plugin would silently fail to re-source. ++if [[ -o KSH_ARRAYS || -o SH_WORD_SPLIT ]]; then ++ emulate zsh -c "source ${(q)${(%):-%N}}" ++ return $? ++fi ++ ++autoload -Uz is-at-least + + if ! is-at-least 4.3.11; then +- print "Zsh-z requires Zsh v4.3.11 or higher." >&2 && exit ++ print "Zsh-z requires Zsh v4.3.11 or higher." >&2 ++ return 1 2> /dev/null || exit 1 + fi + + ############################################################ +@@ -99,6 +119,56 @@ With no ARGUMENT, list the directory history in ascending rank. + fold -s -w $(( COLUMNS > 0 ? COLUMNS : 80 )) >&2 + } + ++############################################################ ++# Canonicalize a path in the manner of `:A' -- normalize it ++# lexically as `:a' does, then resolve symlinks -- without ++# requiring any of the path to exist. ++# ++# `${x:A}' itself cannot be trusted with a missing path on ++# Zsh 4.3.11: when the top-level component of $x does not ++# exist (`/gone/sub'), the realpath machinery segfaults the ++# shell (upstream bug, 4.3.11 only; deeper missing ++# components are handled correctly on every version). So ++# apply `:A' only to the deepest ancestor of the path that ++# exists -- `:A' on an existing path is safe everywhere -- ++# and reattach the missing components verbatim. That ++# reproduces `:A' exactly: `:A' resolves the symlinks in the ++# existing prefix and carries the nonexistent tail ++# unchanged, and the tail cannot contain live symlinks ++# precisely because it does not exist. (A broken symlink ++# stops the ancestor walk without being resolved -- `-e' ++# fails on one -- which also matches `:A', which leaves ++# broken symlinks unresolved.) ++# ++# Arguments: ++# $1 The path to canonicalize ++# ++# Returns the canonical path in $REPLY. ++############################################################ ++_zshz_realpath() { ++ local dir=${1:a} ++ local -a tail ++ ++ # `:h' at its fixed point (`/', or `//' where the OS treats that as ++ # distinct) can climb no higher; if even that much of the path does not ++ # exist, settle for the lexical normalization rather than hand `:A' ++ # something dangerous. ++ while [[ ! -e $dir && $dir != "${dir:h}" ]]; do ++ tail=( "${dir:t}" "${tail[@]}" ) ++ dir=${dir:h} ++ done ++ [[ -e $dir ]] && dir=${dir:A} ++ ++ # `typeset -g': REPLY belongs to the caller by design. A plain assignment ++ # would trip WARN_NESTED_VAR under `ZSHZ_DEBUG', since _zshz_realpath is a ++ # top-level function and thus one of the ones `functions -W' marks. ++ if (( ${#tail} )); then ++ typeset -g REPLY=${dir%/}/${(j:/:)tail} ++ else ++ typeset -g REPLY=$dir ++ fi ++} ++ + # Load zsh/datetime module, if necessary + (( ${+EPOCHSECONDS} )) || zmodload zsh/datetime + +@@ -106,16 +176,26 @@ With no ARGUMENT, list the directory history in ascending rank. + typeset -gA ZSHZ + + # Fallback utilities in case Zsh lacks zsh/files (as is the case with MobaXterm) ++ZSHZ[CHMOD]='chmod' + ZSHZ[CHOWN]='chown' + ZSHZ[MV]='mv' + ZSHZ[RM]='rm' +-# Try to load zsh/files utilities ++ ++# Try to load zsh/files. zf_chown, zf_mv, and zf_rm are usually present in Zsh ++# 4.3.11. zf_chmod only became available in Zsh 5.0, so we load it separately ++# below. If zsh/files is not available at all, we silently fall back to the ++# external utilities chmod, chown, mv, and rm. + if [[ ${builtins[zf_chown]-} != 'defined' || + ${builtins[zf_mv]-} != 'defined' || + ${builtins[zf_rm]-} != 'defined' ]]; then + zmodload -F zsh/files b:zf_chown b:zf_mv b:zf_rm &> /dev/null + fi +-# Use zsh/files, if it is available ++ ++[[ ${builtins[zf_chmod]-} == 'defined' ]] || ++ zmodload -F zsh/files b:zf_chmod &> /dev/null ++ ++# Use zsh/files, if it is available. ++[[ ${builtins[zf_chmod]-} == 'defined' ]] && ZSHZ[CHMOD]='zf_chmod' + [[ ${builtins[zf_chown]-} == 'defined' ]] && ZSHZ[CHOWN]='zf_chown' + [[ ${builtins[zf_mv]-} == 'defined' ]] && ZSHZ[MV]='zf_mv' + [[ ${builtins[zf_rm]-} == 'defined' ]] && ZSHZ[RM]='zf_rm' +@@ -130,8 +210,44 @@ fi + # Determine if zsystem flock is available + zsystem supports flock &> /dev/null && ZSHZ[USE_FLOCK]=1 + +-# Determine if `print -v' is supported +-is-at-least 5.3.0 && ZSHZ[PRINTV]=1 ++# Windows only: how many times to retry a datafile rename that fails. ++# ++# On Cygwin and MSYS2, rename() fails with EBUSY or EACCES whenever another ++# process holds the tempfile or the datafile open without FILE_SHARE_DELETE -- ++# which is precisely what a virus scanner or the search indexer does to a file ++# in the moments after it is created. Since the write path below creates the ++# tempfile and renames it over the datafile microseconds later, that window is ++# wide open. The rename's stderr is discarded there, so a scan that lands in ++# the window silently loses an `--add' or a `-x': no message, no delay, just a ++# directory that never made it into the database. The condition clears in ++# milliseconds, so make a few more attempts before giving up. ++# ++# Everywhere else a failed rename means something real -- ENOSPC, EPERM, a ++# cross-device move -- that retrying cannot fix and would only add latency to, ++# so ZSHZ[MV_RETRIES] stays unset and the loops below make a single attempt, ++# exactly as before. ++# ++# zsh/zselect provides the sub-second delay between attempts without forking ++# /bin/sleep, whose fractional-seconds support is not portable in any case. ++# MobaXterm's cut-down Cygwin does not ship zsh/zselect, so there ++# ZSHZ[MV_RETRY_DELAY] stays unset and the retries happen back to back -- still ++# worth making, since the scanner's handle is often gone by the next attempt. ++# ++# Four retries at 50ms is deliberately modest rather than generous. The rename ++# runs while the lockfile is held, so every millisecond spent retrying is a ++# millisecond other writers spend waiting, and they give up after ++# ZSHZ_LOCK_TIMEOUT (1s by default) -- silently, since their adds are ++# best-effort too. A budget that outlasts a large fraction of that timeout ++# would trade one process's lost write for several others'. Measured on MSYS2 ++# against a handle held open with FILE_SHARE_READ, this recovers renames ++# blocked for up to ~0.3s, comfortably more than a scan of a file this small ++# takes. ++if [[ $OSTYPE == (cygwin|msys) ]]; then ++ ZSHZ[MV_RETRIES]=4 ++ [[ ${modules[zsh/zselect]-} == 'loaded' ]] || zmodload zsh/zselect &> /dev/null ++ # In hundredths of a second, per `zselect -t' ++ [[ ${builtins[zselect]-} == 'defined' ]] && ZSHZ[MV_RETRY_DELAY]=5 ++fi + + ############################################################ + # The Zsh-z Command +@@ -145,6 +261,7 @@ is-at-least 5.3.0 && ZSHZ[PRINTV]=1 + # ZSHZ_DEBUG + # ZSHZ_EXCLUDE_DIRS + # ZSHZ_KEEP_DIRS ++# ZSHZ_LOCK_TIMEOUT + # ZSHZ_MAX_SCORE + # ZSHZ_OWNER + # +@@ -163,42 +280,136 @@ zshz() { + # Allow the user to specify a custom datafile in $ZSHZ_DATA (or legacy $_Z_DATA) + local custom_datafile="${ZSHZ_DATA:-$_Z_DATA}" + ++ # $_zshz_quiet_add marks the automatic bookkeeping add that _zshz_precmd ++ # runs in a `&!' fork before every prompt (_zshz_precmd declares it `local', ++ # so it is visible here only through that one call). A fork cannot ++ # record anything in the parent shell, so it has no way to warn just once: ++ # an unusable $ZSHZ_DATA would otherwise put the same diagnostic on the ++ # terminal at every prompt for the life of the shell. Stay quiet on that ++ # path and leave the complaining to the entry points the user actually ++ # invoked -- including a hand-typed `z --add', which is not marked and so ++ # still reports. ++ local quiet ++ [[ -n ${_zshz_quiet_add-} ]] && quiet=1 ++ + # If a datafile was provided as a standalone file without a directory path +- # print a warning and exit ++ # print a warning and return + if [[ -n ${custom_datafile} && ${custom_datafile} != */* ]]; then +- print "ERROR: You configured a custom Zsh-z datafile (${custom_datafile}), but have not specified its directory." >&2 +- exit ++ (( quiet )) || ++ print "ERROR: You configured a custom Zsh-z datafile (${custom_datafile}), but have not specified its directory." >&2 ++ return 1 + fi + +- # If the user specified a datafile, use that or default to ~/.z +- # If the datafile is a symlink, it gets dereferenced +- local datafile=${${custom_datafile:-$HOME/.z}:A} ++ # Refuse a symlinked datafile while $ZSHZ_OWNER is set, rather than ++ # following it. That variable means root is acting for an unprivileged user ++ # -- the documented `sudo -s' setup -- and the resolution just below ++ # deliberately dereferences a link, so in that configuration Zsh-z would ++ # write the database wherever a name inside the user's own home points, with ++ # root's authority. Nothing has to be raced: the link is planted before the ++ # privileged shell ever starts. Unprivileged use crosses no such boundary and ++ # keeps the dereference, which is what makes pointing `.z' at synced storage ++ # work. ++ # ++ # Every component, not just the last. Resolution walks the whole path, so a ++ # symlinked *parent* redirects it just as effectively: with `link' -> `/etc' ++ # inside a user's home, a datafile of `~/link/passwd' resolves to ++ # `/etc/passwd' and root rewrites it. ++ # ++ # Judged by who owns each link rather than by its mere presence. Symlinked ++ # system directories are ordinary -- `/home' -> `/usr/home' on the BSDs, ++ # `/var' -> `/private/var' on macOS -- and refusing those would break Zsh-z ++ # under $ZSHZ_OWNER on those systems for nothing. Those are root's; what this ++ # has to reject is a link an unprivileged owner could have planted. `zstat ++ # -L' reports the link's own owner rather than its target's, which is the ++ # distinction `-O' cannot make. ++ if [[ -n ${ZSHZ_OWNER:-${_Z_OWNER}} ]]; then ++ local _zshz_df=${custom_datafile:-$HOME/.z} ++ [[ $_zshz_df == /* ]] || _zshz_df="$PWD/$_zshz_df" ++ zmodload -F zsh/stat b:zstat 2> /dev/null ++ local _zshz_pfx _zshz_part _zshz_luid ++ for _zshz_part in ${(s:/:)_zshz_df}; do ++ [[ -n $_zshz_part ]] || continue ++ _zshz_pfx+="/$_zshz_part" ++ [[ -L $_zshz_pfx ]] || continue ++ # Without zsh/stat there is no way to tell whose link this is, so refuse ++ # it rather than guess: this path is privileged by definition. ++ _zshz_luid='' ++ (( ${+builtins[zstat]} )) && ++ _zshz_luid=$(zstat -L +uid "$_zshz_pfx" 2> /dev/null) ++ if [[ $_zshz_luid != 0 ]]; then ++ (( quiet )) || ++ print "ERROR: Zsh-z will not follow the symlink ${_zshz_pfx} on the way to its datafile while ZSHZ_OWNER is set." >&2 ++ return 1 ++ fi ++ done ++ fi + +- # If the datafile is a directory, print a warning and exit ++ # If the user specified a datafile, use that or default to ~/.z ++ # If the datafile is a symlink, it gets dereferenced (except under ++ # $ZSHZ_OWNER, refused just above). Canonicalized with ++ # _zshz_realpath rather than a bare `:A', which would segfault Zsh 4.3.11 ++ # on a $ZSHZ_DATA pointing into a missing top-level directory -- at every ++ # prompt, since this line runs in the backgrounded precmd add. ++ _zshz_realpath "${custom_datafile:-$HOME/.z}" ++ local datafile=$REPLY ++ # Clear REPLY as soon as it is captured: the matching machinery below ++ # relies on it staying empty until a common root or best match is put in ++ # it (_zshz_find_common_root only assigns REPLY when it finds a root), so ++ # a datafile path left in REPLY here would surface as a bogus match. ++ REPLY='' ++ ++ # If the datafile is a directory, print a warning and return + if [[ -d $datafile ]]; then +- print "ERROR: Zsh-z's datafile (${datafile}) is a directory." >&2 +- exit ++ (( quiet )) || ++ print "ERROR: Zsh-z's datafile (${datafile}) is a directory." >&2 ++ return 1 + fi + + # Make sure that the datafile exists before attempting to read it or lock it +- # for writing +- [[ -f $datafile ]] || { mkdir -p "${datafile:h}" && touch "$datafile" } ++ # for writing. Create it with 0600 permissions from the first instant (umask ++ # in a subshell) rather than chmodding it afterward: this creation runs ++ # before the lock is taken, and on Cygwin/MSYS2 a concurrent writer's rename ++ # passes through a window in which the datafile is unlinked or delete- ++ # pending, so any second syscall on the path (chmod) -- or even the creating ++ # open itself -- can fail spuriously. Append mode (>>) creates the file ++ # without truncating one that a concurrent writer has just renamed into ++ # place. The first attempt is silent; if the file still does not exist ++ # afterward (so no concurrent writer supplied it), retry loudly so that real ++ # failures (directory permissions, read-only filesystem) reach the user. ++ [[ -f $datafile ]] || { ++ mkdir -p "${datafile:h}" && ++ ( umask 077; : >> "$datafile" ) 2> /dev/null || ++ [[ -f $datafile ]] || ++ ( umask 077; : >> "$datafile" ) ++ # When $ZSHZ_OWNER is set (e.g. under `sudo -s'), hand the freshly created ++ # file off to that user immediately, so a query-only invocation can't leave ++ # behind a root-owned .z that the normal-user shell can't read. `-h' so a ++ # symlink that appeared since the check above is retitled itself rather ++ # than dereferenced onto its target. ++ local _owner=${ZSHZ_OWNER:-${_Z_OWNER}} ++ [[ -n $_owner ]] && ++ ${ZSHZ[CHOWN]} -h "${_owner}:$(id -ng "${_owner}")" "$datafile" ++ } ++ ++ # If the datafile still does not exist, the loud retry above has already ++ # said why; nothing below -- reading, locking, writing -- can succeed ++ # without it, and each failure would add its own noise. Bailing out here ++ # matters most on Zsh 4.3.11, where the failed `$(< $datafile)' reads ++ # below are fatal to a non-interactive shell. ++ [[ -f $datafile ]] || return 1 + + # Bail if we don't own the datafile and $ZSHZ_OWNER is not set + [[ -z ${ZSHZ_OWNER:-${_Z_OWNER}} && -f $datafile && ! -O $datafile ]] && + return + +- # Load the datafile into an array and parse it +- lines=( ${(f)"$(< $datafile)"} ) +- # Discard entries that are incomplete or incorrectly formatted +- lines=( ${(M)lines:#/*\|[[:digit:]]##[.,]#[[:digit:]]#\|[[:digit:]]##} ) +- + ############################################################ + # Add a path to or remove one from the datafile + # + # Globals: + # ZSHZ + # ZSHZ_EXCLUDE_DIRS ++ # ZSHZ_LOCK_TIMEOUT ++ # ZSHZ_NO_RESOLVE_SYMLINKS + # ZSHZ_OWNER + # + # Arguments: +@@ -206,17 +417,21 @@ zshz() { + # $2 The path to add + ############################################################ + _zshz_add_or_remove_path() { +- local action=${1} ++ local action=$1 + shift + + if [[ $action == '--add' ]]; then + +- # TODO: The following tasks are now handled by _agkozak_precmd. Dead code? ++ # These $HOME / $ZSHZ_EXCLUDE_DIRS guards mirror the ones in ++ # _zshz_precmd, but they are not redundant: precmd filters $PWD as an ++ # early-out (skip the background fork), whereas --add is now a public ++ # entry point and must enforce the same policies as the precmd function. ++ # Keep both in sync. + + # Don't add $HOME + [[ $* == $HOME ]] && return + +- # Don't track directory trees excluded in ZSHZ_EXCLUDE_DIRS ++ # Don't track directory trees excluded in $ZSHZ_EXCLUDE_DIRS + local exclude + for exclude in ${(@)ZSHZ_EXCLUDE_DIRS:-${(@)_Z_EXCLUDE_DIRS}}; do + case $* in +@@ -225,96 +440,381 @@ zshz() { + done + fi + +- # A temporary file that gets copied over the datafile if all goes well +- local tempfile="${datafile}.${RANDOM}" +- +- # See https://github.com/rupa/z/pull/199/commits/ed6eeed9b70d27c1582e3dd050e72ebfe246341c +- if (( ZSHZ[USE_FLOCK] )); then +- +- local lockfd +- +- # Grab exclusive lock (released when function exits) +- zsystem flock -f lockfd "$datafile" 2> /dev/null || return ++ # Resolve the directory to be removed, and confirm a full-database wipe, ++ # *before* taking the lock. Both are independent of the datafile, and the ++ # confirmation is interactive: holding the lock across a `read -q' the user ++ # might walk away from would make concurrent writers in other shells time ++ # out on ZSHZ_LOCK_TIMEOUT and silently drop their adds while the prompt ++ # sits open. A lock should wrap the read-modify-write, never a question. ++ local xdir # Directory to be removed ++ if [[ $action == '--remove' ]]; then ++ # The target is canonicalized without any existence test: an entry ++ # whose directory has since been deleted is exactly the one a user most ++ # wants out of the database. _zshz_realpath resolves a missing path the ++ # way `:A' resolves one -- and, unlike a bare `:A', cannot segfault Zsh ++ # 4.3.11 on a path whose top-level component is gone. (The old ++ # `[[ -d ${...:A} ]]' guard offered no protection there: the `:A' ++ # expands, and crashes, before `-d' ever sees it.) ++ if (( ${ZSHZ_NO_RESOLVE_SYMLINKS:-${_Z_NO_RESOLVE_SYMLINKS}} )); then ++ xdir=${${*:-${PWD}}:a} ++ else ++ _zshz_realpath "${*:-${PWD}}" ++ xdir=$REPLY ++ fi + ++ # Both branches above yield a non-empty absolute path, and that ++ # matters: under `-R' an empty $xdir would collapse the subtree filter ++ # below into `${lines_to_keep:#/**}', which matches every line in the ++ # datafile and erases the lot -- silently, since the whole-database ++ # confirmation just below tests for `/' rather than for emptiness. Keep ++ # this guard in case a future change lets an empty resolution through. ++ [[ -n $xdir ]] || return 1 ++ ++ if (( ${+opts[-R]} )) && [[ $xdir == '/' ]]; then ++ if ! read -q "?Delete entire Zsh-z database? "; then ++ print && return 1 ++ fi ++ fi + fi + +- integer tmpfd +- case $action in +- --add) +- exec {tmpfd}>|"$tempfile" # Open up tempfile for writing +- _zshz_update_datafile $tmpfd "$*" +- local ret=$? +- ;; +- --remove) +- local xdir # Directory to be removed +- +- if (( ${ZSHZ_NO_RESOLVE_SYMLINKS:-${_Z_NO_RESOLVE_SYMLINKS}} )); then +- [[ -d ${${*:-${PWD}}:a} ]] && xdir=${${*:-${PWD}}:a} +- else +- [[ -d ${${*:-${PWD}}:A} ]] && xdir=${${*:-${PWD}}:A} ++ # A temporary file that gets copied over the datafile if all goes well ++ local tempfile="${datafile}.${RANDOM}" lockfile="${datafile}.lock" ++ integer lockfd=0 ++ # The no-flock fallback's lock. Deliberately a *different* name from ++ # $lockfile: a plain file left behind by a flock-capable Zsh would make ++ # `mkdir' fail forever on the same path, deadlocking every later write. ++ local lockdir="${datafile}.lock.d" ++ integer lockdir_held=0 ++ ++ { ++ # Using zsystem flock ++ if (( ZSHZ[USE_FLOCK] )); then ++ ++ # Obtain an exclusive lock on the lockfile. ++ # ++ # Locking the datafile directly would not actually serialize concurrent ++ # writers, since the datafile gets replaced by mv and each new datafile ++ # has a new inode -- so a separate, stable lockfile is needed. ++ # ++ # Bound the lock acquisition (default 1s, override with ZSHZ_LOCK_TIMEOUT) ++ # so a stuck holder can't stall the backgrounded precmd add or freeze a ++ # user's foreground `z --add' / `z -x'. Once the holder dies, the kernel ++ # frees the lock and the next add succeeds automatically -- no manual ++ # `rm ~/.z.lock' needed. ++ # ++ # On timeout we return silently and on purpose: the precmd add is ++ # best-effort and runs backgrounded (`&!'), so there is nowhere useful ++ # to report to -- a message would land on the terminal asynchronously, ++ # mid-keystroke, possibly every prompt. To diagnose a database that has ++ # stopped updating, run a foreground `z --add .' and check `$?': a ++ # nonzero status means the write did not happen -- 2 is a lock- ++ # acquisition timeout (contention, or a raised ZSHZ_LOCK_TIMEOUT is ++ # still too low), 1 is a permissions or ownership problem (e.g. a stale ++ # root-owned lockfile left by an earlier `sudo -s' session, or a ++ # symlinked lockfile refused under $ZSHZ_OWNER). ++ # Create the lockfile 0600-from-birth and silently (umask in a ++ # subshell), mirroring the datafile creation above rather than a bare ++ # `touch' under the ambient umask with unsuppressed stderr. zsystem ++ # flock opens the lockfile O_RDWR, so under `sudo -s' with $ZSHZ_OWNER ++ # the unprivileged user must be able to open it: hand it off at ++ # creation, not only after a successful write -- a timed-out or failed ++ # first write by root would skip the post-write chown and leave a ++ # root-owned lockfile, turning every later user --add / -x into a ++ # silently-swallowed EACCES no-op. The lockfile is deliberately never ++ # removed: unlinking one a waiter has already opened reintroduces the ++ # two-inodes race the stable lockfile exists to prevent. ++ # Under $ZSHZ_OWNER all of this runs with root's authority on a path the ++ # unprivileged owner controls, and every step follows a symlink: `-f' ++ # tests the target, `>>' creates a dangling one, and flock opens it. ++ # $datafile survives a planted link only because the `mv' below replaces ++ # it outright; the lockfile is deliberately never removed, so a symlink ++ # here would persist and be acted on at every subsequent write. Refuse. ++ local _lock_owner=${ZSHZ_OWNER:-${_Z_OWNER}} ++ [[ -n $_lock_owner && -L $lockfile ]] && return 1 ++ if [[ ! -f $lockfile ]]; then ++ ( umask 077; : >> "$lockfile" ) 2> /dev/null ++ [[ -n $_lock_owner ]] && ++ ${ZSHZ[CHOWN]} -h "${_lock_owner}:$(id -ng "${_lock_owner}")" "$lockfile" + fi ++ zsystem flock -t ${ZSHZ_LOCK_TIMEOUT:-1} -f lockfd "$lockfile" 2> /dev/null || return ++ ++ else + +- local -a lines_to_keep +- if (( ${+opts[-R]} )); then +- # Prompt user before deleting entire database +- if [[ $xdir == '/' ]] && ! read -q "?Delete entire Zsh-z database? "; then +- print && return 1 ++ # No `zsystem flock' here. MobaXterm's cut-down Cygwin is the case that ++ # matters -- it ships no `zsh/system' at all -- and until now this path ++ # wrote with nothing serializing it: every writer read its own snapshot ++ # and the last `mv' won. Measured on MobaXterm, an entry added by one of ++ # four concurrent writers went missing in 7 runs out of 10. ++ # ++ # `mkdir' is the portable atomic primitive: it succeeds for exactly one ++ # caller and fails for the rest, with no module behind it. What it does ++ # not give us is the kernel's release-on-death, which is the whole ++ # reason `flock' is preferred where it exists -- so a holder that dies ++ # would wedge every later write. Hence the staleness sweep below. ++ # ++ # Failure to acquire returns 2, the same status the flock branch's ++ # timeout produces and the one the README documents for contention. ++ integer _zshz_deadline=$(( EPOCHSECONDS + ${ZSHZ_LOCK_TIMEOUT:-1} )) ++ local -a _zshz_stale ++ while :; do ++ if mkdir "$lockdir" 2> /dev/null; then ++ lockdir_held=1 ++ break + fi +- # All of the lines that don't match the directory to be deleted +- lines_to_keep=( ${lines:#${xdir}\|*} ) +- # Or its subdirectories +- lines_to_keep=( ${lines_to_keep:#${xdir%/}/**} ) +- else +- # All of the lines that don't match the directory to be deleted +- lines_to_keep=( ${lines:#${xdir}\|*} ) +- fi +- if [[ $lines != "$lines_to_keep" ]]; then +- lines=( $lines_to_keep ) +- else +- return 1 # The $PWD isn't in the datafile +- fi +- exec {tmpfd}>|"$tempfile" # Open up tempfile for writing +- print -u $tmpfd -l -- $lines +- local ret=$? +- ;; +- esac ++ # Break a lock nobody can still be holding. A write is a matter of ++ # milliseconds, so a lock directory older than 30 seconds means its ++ # owner died without releasing it. `mkdir' stamps the mtime at ++ # creation and no holder touches it afterwards, so the age is the ++ # hold time. `$lockdir' expands literally here -- only the qualifier ++ # is glob syntax -- so a datafile path containing `[' or `*' is safe. ++ _zshz_stale=( ${lockdir}(Nms+30) ) ++ if (( ${#_zshz_stale} )); then ++ rmdir "$lockdir" 2> /dev/null && continue ++ fi ++ (( EPOCHSECONDS >= _zshz_deadline )) && return 2 ++ # No `zselect' on the platforms that land here, so this costs a fork. ++ # It is the slow path already, and spinning would be worse. ++ sleep 0.05 2> /dev/null || : ++ done + +- if (( tmpfd != 0 )); then +- # Close tempfile +- exec {tmpfd}>&- +- fi ++ fi + +- if (( ret != 0 )); then +- # Avoid clobbering the datafile if the write to tempfile failed +- ${ZSHZ[RM]} -f "$tempfile" +- return $ret +- fi ++ # Read the datafile only after obtaining the lock, so concurrent --add ++ # calls don't all act on the same stale snapshot. ++ lines=( ${(f)"$(< $datafile)"} ) ++ # Discard entries that are incomplete or incorrectly formatted ++ lines=( ${(M)lines:#/*\|[[:digit:]]##[.,]#[[:digit:]]#\|[[:digit:]]##} ) ++ ++ # Hold the fd in an *unset* scalar, not `integer tmpfd' (which seeds it ++ # with 0). On some Zsh builds, `exec {tmpfd}>|...' refuses to clobber a ++ # parameter already holding a number that names an open fd -- and 0 is ++ # stdin, always open -- yielding "can't clobber parameter tmpfd ++ # containing file descriptor 0". An empty scalar isn't a valid fd, so ++ # the guard never fires. See https://github.com/agkozak/zsh-z/issues/81 ++ local tmpfd ++ case $action in ++ --add) ++ # When zf_chmod isn't available (Zsh 4.3.11), avoid the ++ # ~900us fork+execve of external /usr/bin/chmod on every ++ # write. Create the tempfile with mode 0600 from the start ++ # via `umask 077' inside a subshell -- the umask change is ++ # contained to the forked child process and the OS prevents ++ # it from leaking back to the parent. Subshell fork without ++ # exec is ~50us, ~18x cheaper than the chmod fallback. ++ if [[ ${ZSHZ[CHMOD]} == 'zf_chmod' ]]; then ++ exec {tmpfd}>|"$tempfile" # Open up tempfile for writing ++ # Fail closed. The tempfile is born with the ambient umask (0666 ++ # under `umask 000'), and it is this inode -- not the datafile's -- ++ # that the rename below publishes, so a chmod whose failure went ++ # unnoticed would replace a 0600 datafile with a world-readable one ++ # and still report success. Nothing has been written yet, so ++ # there is no salvage: drop the tempfile and leave the database as ++ # it was. ++ if ! ${ZSHZ[CHMOD]} 600 "$tempfile"; then ++ exec {tmpfd}>&- ++ ${ZSHZ[RM]} -f "$tempfile" 2> /dev/null ++ return 1 ++ fi ++ _zshz_update_datafile $tmpfd "$*" ++ else ++ ( umask 077 ++ exec {tmpfd}>|"$tempfile" ++ _zshz_update_datafile $tmpfd "$*" ) ++ fi ++ local ret=$? ++ ;; ++ --remove) ++ # $xdir was resolved before the lock, and for `-xR /' the ++ # whole-database wipe was already confirmed there. ++ local -a lines_to_keep ++ if (( ${+opts[-R]} )); then ++ # All of the lines that don't match the directory to be deleted ++ lines_to_keep=( ${lines:#${xdir}\|*} ) ++ # Or its subdirectories ++ lines_to_keep=( ${lines_to_keep:#${xdir%/}/**} ) ++ else ++ # All of the lines that don't match the directory to be deleted ++ lines_to_keep=( ${lines:#${xdir}\|*} ) ++ fi ++ if [[ $lines != "$lines_to_keep" ]]; then ++ lines=( $lines_to_keep ) ++ else ++ return 1 # The $PWD isn't in the datafile ++ fi ++ # Same umask-subshell pattern as --add: avoid the external ++ # chmod when zf_chmod isn't available. ++ if [[ ${ZSHZ[CHMOD]} == 'zf_chmod' ]]; then ++ exec {tmpfd}>|"$tempfile" # Open up tempfile for writing ++ # Fail closed, exactly as on the --add path above. ++ if ! ${ZSHZ[CHMOD]} 600 "$tempfile"; then ++ exec {tmpfd}>&- ++ ${ZSHZ[RM]} -f "$tempfile" 2> /dev/null ++ return 1 ++ fi ++ # `-r': $lines are verbatim on-disk lines (the datafile stores ++ # literal paths), so they must be written back unchanged. Without ++ # `-r', print would collapse an escape -- e.g. a literal `\t' in a ++ # path into a tab -- silently corrupting bystander entries. ++ print -u $tmpfd -rl -- $lines ++ else ++ ( umask 077; print -rl -- $lines >| "$tempfile" ) ++ fi ++ local ret=$? ++ ;; ++ esac + +- local owner +- owner=${ZSHZ_OWNER:-${_Z_OWNER}} ++ if [[ -n $tmpfd ]]; then ++ # Close tempfile ++ exec {tmpfd}>&- ++ fi + +- if (( ZSHZ[USE_FLOCK] )); then +- # An unusual case: if inside Docker container where datafile could be bind +- # mounted +- if [[ -f '/.dockerenv' || ( -r '/proc/1/cgroup' && "$(< '/proc/1/cgroup')" == *docker* ) ]]; then +- print "$(< "$tempfile")" > "$datafile" 2> /dev/null ++ if (( ret != 0 )); then ++ # Avoid clobbering the datafile if the write to tempfile failed + ${ZSHZ[RM]} -f "$tempfile" +- # All other cases +- else +- ${ZSHZ[MV]} "$tempfile" "$datafile" 2> /dev/null || +- ${ZSHZ[RM]} -f "$tempfile" ++ return $ret + fi + +- if [[ -n $owner ]]; then +- ${ZSHZ[CHOWN]} ${owner}:"$(id -ng ${owner})" "$datafile" +- fi +- else +- if [[ -n $owner ]]; then +- ${ZSHZ[CHOWN]} "${owner}":"$(id -ng "${owner}")" "$tempfile" ++ integer write_ret chown_ret mv_attempts ++ local owner ++ owner=${ZSHZ_OWNER:-${_Z_OWNER}} ++ ++ if (( ZSHZ[USE_FLOCK] )); then ++ # An unusual case: if inside Docker container where datafile could be bind ++ # mounted ++ if [[ -f '/.dockerenv' || ( -r '/proc/1/cgroup' && "$(< '/proc/1/cgroup')" == *docker* ) ]]; then ++ # Secure the datafile *before* its contents land. This branch writes ++ # in place instead of renaming an already-0600 tempfile over the ++ # path, so asserting the mode afterwards -- as this did -- leaves a ++ # bind-mounted datafile that arrived permissive readable for the ++ # length of the write, and leaves it readable for good if the chmod ++ # fails and nothing checks. The mode carries across the truncating ++ # write below, which reuses this same inode. ++ if ! ${ZSHZ[CHMOD]} 600 "$datafile" 2> /dev/null; then ++ ${ZSHZ[RM]} -f "$tempfile" 2> /dev/null ++ return 1 ++ fi ++ # This is the one write path where a symlink at $datafile redirects ++ # real database content: the sibling branch renames a finished ++ # tempfile over the path, and a rename *replaces* a link rather than ++ # writing through it, while `>|' follows one. Under $ZSHZ_OWNER that ++ # content goes out with root's authority to a path an unprivileged ++ # owner controls, so a `-L' test ahead of the write is not enough -- ++ # the path can be swapped in between. ++ # ++ # `sysopen -o nofollow' settles it atomically, at open time, and the ++ # write goes through that descriptor. If it is unavailable (Zsh ++ # 4.3.11 has `zsystem flock' but no `sysopen' at all, and O_NOFOLLOW ++ # is not universal) or it refuses the open, the privileged write is ++ # refused rather than retried by a following one: this degrades to ++ # failing closed, never to writing unsafely. Without an owner set no ++ # privilege is crossed and the plain redirection stands. ++ # ++ # `chmod' above stays path-based -- Zsh has no `fchmod' -- so a swap ++ # can still misdirect it. Setting the mode on the wrong file is a far ++ # smaller matter than writing the database into it, and the write is ++ # what this closes. ++ local _zshz_dfd ++ if [[ -n $owner ]]; then ++ if (( ${+builtins[sysopen]} )) && ++ sysopen -o trunc,nofollow -w -u _zshz_dfd "$datafile" 2> /dev/null ++ then ++ print -u $_zshz_dfd -r -- "$(< "$tempfile")" 2> /dev/null ++ write_ret=$? ++ exec {_zshz_dfd}>&- ++ else ++ ${ZSHZ[RM]} -f "$tempfile" 2> /dev/null ++ return 1 ++ fi ++ else ++ # `-r': re-emit the tempfile's already-literal contents byte-for-byte. ++ print -r -- "$(< "$tempfile")" >| "$datafile" 2> /dev/null ++ write_ret=$? ++ fi ++ ${ZSHZ[RM]} -f "$tempfile" 2> /dev/null ++ # All other cases ++ else ++ # Retry a rename that a Windows sharing violation turned away; see ++ # the ZSHZ[MV_RETRIES] comment at the top of this file. Off Windows ++ # this loop makes the same single attempt it always has. Retrying is ++ # safe here: the rename happens under the lock, so no other writer ++ # can slip in between attempts. ++ while :; do ++ if ${ZSHZ[MV]} "$tempfile" "$datafile" 2> /dev/null; then ++ write_ret=0 ++ else ++ write_ret=$? ++ fi ++ (( write_ret == 0 )) && break ++ (( mv_attempts++ >= ${ZSHZ[MV_RETRIES]:-0} )) && break ++ if (( ${+ZSHZ[MV_RETRY_DELAY]} )); then ++ zselect -t ${ZSHZ[MV_RETRY_DELAY]} || : ++ fi ++ done ++ (( write_ret != 0 )) && ${ZSHZ[RM]} -f "$tempfile" 2> /dev/null ++ fi ++ # Preserve the write failure itself; best-effort tempfile cleanup must not ++ # turn a failed persist into a successful return. ++ (( write_ret == 0 )) || return $write_ret ++ ++ if [[ -n $owner ]]; then ++ # Chown the lockfile alongside the datafile: zsystem flock opens it ++ # O_RDWR, so if root creates it first under sudo -s, the unprivileged ++ # $ZSHZ_OWNER user's flock attempts would fail with EACCES (silently ++ # swallowed), turning --add and -x into no-ops. ++ # `-h' on both: the lockfile is never replaced, so a symlink planted ++ # there outlives any one write, and $datafile can be relinked in the ++ # window between the `mv' above and this line. Retitling the link ++ # itself -- which the owner already owns -- costs nothing, while ++ # dereferencing hands root's authority to whatever it names. ++ ${ZSHZ[CHOWN]} -h "${owner}:$(id -ng "${owner}")" "$datafile" "$lockfile" ++ chown_ret=$? ++ # Surface post-write chown failures too: the current write landed, but a ++ # wrong owner can break the next locked write. ++ (( chown_ret == 0 )) || return $chown_ret ++ fi ++ else ++ if [[ -n $owner ]]; then ++ ${ZSHZ[CHOWN]} -h "${owner}:$(id -ng "${owner}")" "$tempfile" ++ chown_ret=$? ++ if (( chown_ret != 0 )); then ++ # In the no-flock path, chown happens before the move, so clean up the ++ # tempfile and leave the live database untouched. ++ ${ZSHZ[RM]} -f "$tempfile" 2> /dev/null ++ return $chown_ret ++ fi ++ fi ++ # Same Windows sharing-violation retry as the flock branch above. This ++ # path is the one MobaXterm's cut-down Cygwin takes, and it has neither ++ # zsystem flock nor zsh/zselect, so the retries there run back to back. ++ while :; do ++ if ${ZSHZ[MV]} -f "$tempfile" "$datafile" 2> /dev/null; then ++ write_ret=0 ++ else ++ write_ret=$? ++ fi ++ (( write_ret == 0 )) && break ++ (( mv_attempts++ >= ${ZSHZ[MV_RETRIES]:-0} )) && break ++ if (( ${+ZSHZ[MV_RETRY_DELAY]} )); then ++ zselect -t ${ZSHZ[MV_RETRY_DELAY]} || : ++ fi ++ done ++ if (( write_ret != 0 )); then ++ ${ZSHZ[RM]} -f "$tempfile" 2> /dev/null ++ return $write_ret ++ fi + fi +- ${ZSHZ[MV]} -f "$tempfile" "$datafile" 2> /dev/null || +- ${ZSHZ[RM]} -f "$tempfile" +- fi ++ } always { ++ # zsystem flock -f opens a real fd; explicitly unlock it so repeated ++ # foreground `z --add' / `z -x' invocations in the interactive shell ++ # don't leak lock descriptors and stall peers. (A backgrounded precmd ++ # child releases its fd on exit regardless; this matters for the parent.) ++ (( lockfd != 0 )) && zsystem flock -u $lockfd 2> /dev/null ++ # Release the mkdir lock on every exit from the block above, including ++ # the early `return's -- unlike an fd, a directory outlives the process ++ # that made it, so a missed release here is a wedged database rather than ++ # a leaked descriptor. Only if this call is the one that took it. ++ (( lockdir_held )) && rmdir "$lockdir" 2> /dev/null ++ } + + # In order to make z -x work, we have to disable zsh-z's adding + # to the database until the user changes directory and the +@@ -346,31 +846,35 @@ zshz() { + # See https://github.com/rupa/z/issues/246 + local add_path=${(q)2} + +- local -a existing_paths + local now=$EPOCHSECONDS line dir + local path_field rank_field time_field count x ++ local -i keep + + rank[$add_path]=1 + time[$add_path]=$now + +- # Remove paths from database if they no longer exist + for line in $lines; do +- if [[ ! -d ${line%%\|*} ]]; then ++ path_field=${line%%\|*} ++ ++ # Filter non-existent paths (honoring ZSHZ_KEEP_DIRS) inline so ++ # we walk $lines once instead of twice. The `keep=1; break' also ++ # fixes a latent bug: the previous existence-check loop had no ++ # `break' after appending, so a non-existent path matching ++ # multiple ZSHZ_KEEP_DIRS patterns was processed more than once. ++ if [[ ! -d $path_field ]]; then ++ keep=0 + for dir in ${(@)ZSHZ_KEEP_DIRS}; do +- if [[ ${line%%\|*} == ${dir}/* || +- ${line%%\|*} == $dir || +- $dir == '/' ]]; then +- existing_paths+=( $line ) ++ if [[ $path_field == ${dir}/* || $path_field == $dir || $dir == '/' ]]; then ++ keep=1 ++ break + fi + done +- else +- existing_paths+=( $line ) ++ (( keep )) || continue + fi +- done +- lines=( $existing_paths ) + +- for line in $lines; do +- path_field=${(q)line%%\|*} ++ # Quote in place: assoc-array keys need shell-special chars ++ # backslash-escaped (rupa/z#246). ++ path_field=${(q)path_field} + rank_field=${${line%\|*}#*\|} + time_field=${line##*\|} + +@@ -378,8 +882,13 @@ zshz() { + (( rank_field < 1 )) && continue + + if [[ $path_field == $add_path ]]; then +- rank[$path_field]=$rank_field +- (( rank[$path_field]++ )) ++ # Compute the new rank with a scalar expression, not `(( rank[$key]++ ))'. ++ # The keys are `${(q)}'-quoted (rupa/z#246); a math-context subscript ++ # runs its key through the arithmetic lexer, which strips a backslash ++ # level and so misses any key containing `$ \ [ ] ( )' or a backtick -- ++ # incrementing a phantom raw-keyed entry and leaving the real one stuck. ++ # An assignment subscript expands the key literally, so it is safe. ++ rank[$path_field]=$(( rank_field + 1 )) + time[$path_field]=$now + else + rank[$path_field]=$rank_field +@@ -387,16 +896,33 @@ zshz() { + fi + (( count += rank_field )) + done ++ local -a out + if (( count > ${ZSHZ_MAX_SCORE:-${_Z_MAX_SCORE:-9000}} )); then + # Aging + for x in ${(k)rank}; do +- print -u $fd -- "$x|$(( 0.99 * rank[$x] ))|${time[$x]}" || return 1 ++ # `${rank[$x]}', not a bare `rank[$x]' math subscript: the keys are ++ # `${(q)}'-quoted (rupa/z#246), and a math-context subscript would run ++ # the key through the arithmetic lexer, stripping a backslash level and ++ # missing any key with `$ \ [ ] ( )' or a backtick -- yielding 0, which ++ # the `rank_field < 1' drop above then erases on the next write. The ++ # expansion substitutes the numeric value before the math parser runs. ++ out+=( "$x|$(( 0.99 * ${rank[$x]} ))|${time[$x]}" ) + done + else + for x in ${(k)rank}; do +- print -u $fd -- "$x|${rank[$x]}|${time[$x]}" || return 1 ++ out+=( "$x|${rank[$x]}|${time[$x]}" ) + done + fi ++ # Deliberately NO `-r' here, unlike every other datafile write. The keys in ++ # $out are `${(q)}'-quoted (assoc-array keys need shell-special chars ++ # backslash-escaped -- rupa/z#246), and a plain `print' strips exactly one ++ # backslash level back off, so what lands on disk is the literal path the ++ # rest of the code expects. Adding `-r' would store the still-quoted form ++ # (e.g. `/foo\ bar'), which the read path -- it does not unquote -- would ++ # then fail to match. The verbatim-passthrough writes in ++ # `_zshz_add_or_remove_path' DO use `-r' because their input is already ++ # literal; this one is not. ++ print -u $fd -l -- $out || return 1 + } + + ############################################################ +@@ -418,21 +944,29 @@ zshz() { + # Replace spaces in the search string with asterisks for globbing + 1=${1//[[:space:]]/*} + ++ # Hoist loop-invariants out of the per-line loop -- $1 and ++ # $ZSHZ_TRAILING_SLASH don't change inside the loop, so the ++ # lowercase comparison and the trailing-slash branch were pure ++ # waste when recomputed N times. `query_lower' lets the case- ++ # insensitive branch glob against a precompiled lowercase pattern. ++ local query_lower=${1:l} ++ local -i is_lowercase_query=0 ++ [[ $1 == $query_lower ]] && is_lowercase_query=1 ++ local -i trail=${ZSHZ_TRAILING_SLASH:-0} ++ + for line in $lines; do + + path_field=${line%%\|*} + + path_field_normalized=$path_field +- if (( ZSHZ_TRAILING_SLASH )); then +- path_field_normalized=${path_field%/}/ +- fi ++ (( trail )) && path_field_normalized=${path_field%/}/ + + # If the search string is all lowercase, the search will be case-insensitive +- if [[ $1 == "${1:l}" && ${path_field_normalized:l} == *${~1}* ]]; then +- print -- $path_field ++ if (( is_lowercase_query )) && [[ ${path_field_normalized:l} == *${~query_lower}* ]]; then ++ print -r -- $path_field + # Otherwise, case-sensitive + elif [[ $path_field_normalized == *${~1}* ]]; then +- print -- $path_field ++ print -r -- $path_field + fi + + done +@@ -440,62 +974,18 @@ zshz() { + # insensitively. + } + +- ############################################################ +- # `print' or `printf' to REPLY +- # +- # Variable assignment through command substitution, of the +- # form +- # +- # foo=$( bar ) +- # +- # requires forking a subshell; on Cygwin/MSYS2/WSL1 that can +- # be surprisingly slow. Zsh-z avoids doing that by printing +- # values to the variable REPLY. Since Zsh v5.3.0 that has +- # been possible with `print -v'; for earlier versions of the +- # shell, the values are placed on the editing buffer stack +- # and then `read' into REPLY. +- # +- # Globals: +- # ZSHZ +- # +- # Arguments: +- # Options and parameters for `print' +- ############################################################ +- _zshz_printv() { +- # NOTE: For a long time, ZSH's `print -v' had a tendency +- # to mangle multibyte strings: +- # +- # https://www.zsh.org/mla/workers/2020/msg00307.html +- # +- # The bug was fixed in late 2020: +- # +- # https://github.com/zsh-users/zsh/commit/b6ba74cd4eaec2b6cb515748cf1b74a19133d4a4#diff-32bbef18e126b837c87b06f11bfc61fafdaa0ed99fcb009ec53f4767e246b129 +- # +- # In order to support shells with the bug, we must use a form of `printf`, +- # which does not exhibit the undesired behavior. See +- # +- # https://www.zsh.org/mla/workers/2020/msg00308.html +- +- if (( ZSHZ[PRINTV] )); then +- builtin print -v REPLY -f %s $@ +- else +- builtin print -z $@ +- builtin read -rz REPLY +- fi +- } +- + ############################################################ + # If matches share a common root, find it, and put it in + # REPLY for _zshz_output to use. + # + # Arguments: +- # $1 Name of associative array of matches and ranks ++ # $@ Candidate paths + ############################################################ + _zshz_find_common_root() { + local -a common_matches + local x short + +- common_matches=( ${(@Pk)1} ) ++ common_matches=( "$@" ) + + for x in ${(@)common_matches}; do + if [[ -z $short ]] || (( $#x < $#short )) || [[ $x != ${short}/* ]]; then +@@ -509,7 +999,7 @@ zshz() { + [[ $x != $short* ]] && return + done + +- _zshz_printv -- $short ++ REPLY=$short + } + + ############################################################ +@@ -521,6 +1011,7 @@ zshz() { + # 3) Put a common root or best match into REPLY + # + # Globals: ++ # ZSHZ_TILDE + # ZSHZ_UNCOMMON + # + # Arguments: +@@ -532,66 +1023,110 @@ zshz() { + _zshz_output() { + + local match_array=$1 match=$2 format=$3 +- local common k x ++ local common x v + local -a descending_list output +- local -A output_matches +- +- output_matches=( ${(Pkv)match_array} ) + +- _zshz_find_common_root $match_array ++ _zshz_find_common_root ${(@Pk)match_array} + common=$REPLY ++ # Clear REPLY once the common root is captured: the caller reads REPLY as ++ # the jump target, so a value left over here would make `z -l ' ++ # change directory after listing. The default arm below overwrites REPLY ++ # deliberately; the completion and list arms must leave it empty. ++ REPLY='' ++ ++ # Iterate the caller's matches/imatches array as flat key-value ++ # pairs via ${(@Pkv)...} instead of copying into a local ++ # associative array. Avoids the hash-table allocation and K ++ # inserts that the copy required. ++ local -a kv ++ local -i i ++ kv=( ${(@Pkv)match_array} ) + + case $format in + + completion) +- for k in ${(@k)output_matches}; do +- _zshz_printv -f "%.2f|%s" ${output_matches[$k]} $k +- descending_list+=( ${(f)REPLY} ) +- REPLY='' ++ # Build "sortkey|path" rows, sort by the leading key descending, then ++ # strip the key+'|' prefix to keep just the paths (the key is never ++ # user-visible). The key MUST be an integer: `${(@On)}' numeric sort ++ # compares each run of digits on its own, so a raw float rank orders by ++ # its fractional digit-run rather than its value -- "100.5" would sort ++ # below "100.25" (5 < 25). Scale by 100 and drop the decimal so two ++ # digits of resolution survive (what the old `%.2f' rows preserved) as a ++ # single integer digit-run. (Negative `-t' ranks still sort by ++ # magnitude, since `n' ignores the sign -- unchanged from the `%.2f' ++ # rows, i.e. a pre-existing quirk, not introduced here.) ++ local sortkey ++ for ((i=1; i<=${#kv}; i+=2)); do ++ sortkey=$(( kv[i+1] * 100 )) ++ descending_list+=( "${sortkey%.*}|${kv[i]}" ) + done + descending_list=( ${${(@On)descending_list}#*\|} ) +- print -l $descending_list ++ print -rl -- $descending_list + ;; + + list) ++ # The bare `z -l' fast path (no query) inlines an equivalent ++ # formatting block straight on $lines to skip this pipeline -- ++ # keep the two list formatters in sync. + local path_to_display +- for x in ${(k)output_matches}; do +- if (( ${output_matches[$x]} )); then +- path_to_display=$x +- (( ZSHZ_TILDE )) && +- path_to_display=${path_to_display/#${HOME}/\~} +- _zshz_printv -f "%-10d %s\n" ${output_matches[$x]} $path_to_display +- output+=( ${(f)REPLY} ) +- REPLY='' +- fi ++ local -a displayed_paths ++ for ((i=1; i<=${#kv}; i+=2)); do ++ x=${kv[i]} v=${kv[i+1]} ++ (( v )) || continue ++ displayed_paths+=( $x ) ++ path_to_display=$x ++ (( ZSHZ_TILDE )) && ++ path_to_display=${path_to_display/#${HOME}/\~} ++ # Right-pad the integer rank to 10 chars, as `printf "%-10d %s\n"' ++ # used to, but in parameter expansion. The padding must be ++ # conditional: `%-10d' never shortened anything, but a bare ++ # `${(r:10:)}' *truncates* a rank longer than 10 characters -- an ++ # 11-character `-t' rank (sign + 10 digits, e.g. from a zeroed or ++ # hand-imported time field more than ~31.7 years old) or a frecency ++ # rank inflated by a raised $ZSHZ_MAX_SCORE would lose its last ++ # digits, garbling both the displayed figure and the numeric sort ++ # below. The `%.*' strip drops frecency's decimal tail ++ # ("30000.0" -> "30000") to match what `%-10d' produced. ++ v=${v%.*} ++ (( ${#v} < 10 )) && v=${(r:10:)v} ++ output+=( "$v $path_to_display" ) + done ++ # Recompute the common root over the entries that survived the rank ++ # filter above: $common, computed at the top of this function, ++ # covers *every* match -- including rank-0 entries hidden from the ++ # listing -- so it could name a root the visible entries do not ++ # share. The bare `z -l' fast path filters rank-0 entries before ++ # looking for a root, and the two formatters must produce identical ++ # output. (The jump arm below still uses the full-match root: what ++ # `z foo' jumps to is a separate question from what a listing ++ # displays.) ++ common='' ++ if (( $#displayed_paths )); then ++ _zshz_find_common_root $displayed_paths ++ common=$REPLY ++ # A listing must never leave a jump target in REPLY. ++ REPLY='' ++ fi + if [[ -n $common ]]; then + (( ZSHZ_TILDE )) && common=${common/#${HOME}/\~} + (( $#output > 1 )) && printf "%-10s %s\n" 'common:' $common + fi +- # -lt +- if (( $+opts[-t] )); then +- for x in ${(@On)output}; do +- print -- $x +- done +- # -lr +- elif (( $+opts[-r] )); then +- for x in ${(@on)output}; do +- print -- $x +- done +- # -l +- else +- for x in ${(@on)output}; do +- print $x +- done ++ if (( $#output )); then ++ # -lt: most-recent first (descending); -lr and default -l: ++ # ascending rank. ++ if (( $+opts[-t] )); then ++ print -rl -- ${(@On)output} ++ else ++ print -rl -- ${(@on)output} ++ fi + fi + ;; + + *) + if (( ! ZSHZ_UNCOMMON )) && [[ -n $common ]]; then +- _zshz_printv -- $common ++ REPLY=$common + else +- _zshz_printv -- ${(P)match} ++ REPLY=${(P)match} + fi + ;; + esac +@@ -606,63 +1141,85 @@ zshz() { + # ZSHZ + # ZSHZ_CASE + # ZSHZ_KEEP_DIRS +- # ZSHZ_OWNER ++ # ZSHZ_TRAILING_SLASH + # + # Arguments: +- # #1 Pattern to match ++ # $1 Pattern to match + # $2 Matching method (rank, time, or [default] frecency) + # $3 Output format (completion, list, or [default] store +- # in REPLY ++ # in REPLY) + ############################################################ + _zshz_find_matches() { + setopt LOCAL_OPTIONS NO_EXTENDED_GLOB + + local fnd=$1 method=$2 format=$3 + +- local -a existing_paths +- local line dir path_field rank_field time_field rank dx escaped_path_field ++ local line dir path_field rank_field time_field rank dx + local -A matches imatches + local best_match ibest_match hi_rank=-9999999999 ihi_rank=-9999999999 ++ local -i keep ++ ++ # Hoist loop-invariants. $fnd, $1, and $ZSHZ_TRAILING_SLASH don't ++ # change inside the per-line loop, so the space-to-glob ++ # substitution, the `${1:l} == $1' check, and the `:l' on $q were ++ # pure waste when recomputed N times. The `q_lower' precompute ++ # lets `${~q_lower}' replace `${~q:l}' in the case-insensitive ++ # branches: same expanded pattern, compiled once. ++ local q=${fnd//[[:space:]]/\*} ++ local q_lower=${q:l} ++ local -i is_lowercase_query=0 ++ [[ ${1:l} == $1 ]] && is_lowercase_query=1 ++ local -i trail=${ZSHZ_TRAILING_SLASH:-0} ++ local now=$EPOCHSECONDS ++ ++ # This flag is consumed by the ZSHZ_UNCOMMON trimming block, which must know ++ # whether the match it is about to trim was found case-insensitively. Clear ++ # it at the start of every search so a value left over from a previous call ++ # -- e.g. a tab-completion, which sets it but never runs the trimming block ++ # that would reset it -- can't steer this search into the wrong branch. The ++ # authoritative value is set below, from whichever match actually wins. ++ ZSHZ[CASE_INSENSITIVE]=0 + +- # Remove paths from database if they no longer exist + for line in $lines; do +- if [[ ! -d ${line%%\|*} ]]; then ++ path_field=${line%%\|*} ++ ++ # Filter non-existent paths (honoring ZSHZ_KEEP_DIRS) inline so we ++ # walk $lines once instead of twice. The `keep=1; break' inside the ++ # inner loop also fixes a latent bug: the previous existence-check ++ # loop had no `break' after appending, so a non-existent path that ++ # matched multiple ZSHZ_KEEP_DIRS patterns was processed more than ++ # once. ++ if [[ ! -d $path_field ]]; then ++ keep=0 + for dir in ${(@)ZSHZ_KEEP_DIRS}; do +- if [[ ${line%%\|*} == ${dir}/* || +- ${line%%\|*} == $dir || +- $dir == '/' ]]; then +- existing_paths+=( $line ) ++ if [[ $path_field == ${dir}/* || $path_field == $dir || $dir == '/' ]]; then ++ keep=1 ++ break + fi + done +- else +- existing_paths+=( $line ) ++ (( keep )) || continue + fi +- done +- lines=( $existing_paths ) + +- for line in $lines; do +- path_field=${line%%\|*} + rank_field=${${line%\|*}#*\|} + time_field=${line##*\|} + + case $method in + rank) rank=$rank_field ;; +- time) (( rank = time_field - EPOCHSECONDS )) ;; ++ time) (( rank = time_field - now )) ;; + *) +- # Frecency routine +- (( dx = EPOCHSECONDS - time_field )) ++ # Frecency routine: weight a path's stored frequency (rank_field) ++ # by how recently it was visited (dx seconds ago). 10000 scales ++ # the result into integer-comparable territory; the 3.75 / (...) ++ # term decays from 3 (just now) toward 0 as dx grows, so older ++ # paths lose rank. This is the canonical copy; the bare `z -l' ++ # fast path inlines the same formula -- keep the two in sync. ++ (( dx = now - time_field )) + rank=$(( 10000 * rank_field * (3.75/( (0.0001 * dx + 1) + 0.25)) )) + ;; + esac + +- # Use spaces as wildcards +- local q=${fnd//[[:space:]]/\*} +- +- # If $ZSHZ_TRAILING_SLASH is set, use path_field with a trailing slash for matching. + local path_field_normalized=$path_field +- if (( ZSHZ_TRAILING_SLASH )); then +- path_field_normalized=${path_field%/}/ +- fi ++ (( trail )) && path_field_normalized=${path_field%/}/ + + # If $ZSHZ_CASE is 'ignore', be case-insensitive. + # +@@ -671,33 +1228,32 @@ zshz() { + # + # Otherwise, the default behavior of Zsh-z is to match case-sensitively if + # possible, then to fall back on a case-insensitive match if possible. +- if [[ $ZSHZ_CASE == 'smart' && ${1:l} == $1 && +- ${path_field_normalized:l} == ${~q:l} ]]; then ++ # ++ # Track best_match / ibest_match directly from $rank in each branch so ++ # we never have to math-subscript matches[] / imatches[] -- the math ++ # parser interprets shell-special chars in associative-array keys as ++ # syntax (rupa/z#246), and the workaround used to be a seven-char ++ # escape pass on every line. Comparing the $rank scalar to the running ++ # max sidesteps the subscript entirely. ++ if [[ $ZSHZ_CASE == 'smart' ]] && (( is_lowercase_query )) && ++ [[ ${path_field_normalized:l} == ${~q_lower} ]]; then + imatches[$path_field]=$rank ++ if (( rank > ihi_rank )); then ++ ibest_match=$path_field ++ ihi_rank=$rank ++ fi + elif [[ $ZSHZ_CASE != 'ignore' && $path_field_normalized == ${~q} ]]; then + matches[$path_field]=$rank +- elif [[ $ZSHZ_CASE != 'smart' && ${path_field_normalized:l} == ${~q:l} ]]; then ++ if (( rank > hi_rank )); then ++ best_match=$path_field ++ hi_rank=$rank ++ fi ++ elif [[ $ZSHZ_CASE != 'smart' && ${path_field_normalized:l} == ${~q_lower} ]]; then + imatches[$path_field]=$rank +- fi +- +- # Escape characters that would cause "invalid subscript" errors +- # when accessing the associative array. +- escaped_path_field=${path_field//'\'/'\\'} +- escaped_path_field=${escaped_path_field//'`'/'\`'} +- escaped_path_field=${escaped_path_field//'('/'\('} +- escaped_path_field=${escaped_path_field//')'/'\)'} +- escaped_path_field=${escaped_path_field//'['/'\['} +- escaped_path_field=${escaped_path_field//']'/'\]'} +- +- if (( matches[$escaped_path_field] )) && +- (( matches[$escaped_path_field] > hi_rank )); then +- best_match=$path_field +- hi_rank=${matches[$escaped_path_field]} +- elif (( imatches[$escaped_path_field] )) && +- (( imatches[$escaped_path_field] > ihi_rank )); then +- ibest_match=$path_field +- ihi_rank=${imatches[$escaped_path_field]} +- ZSHZ[CASE_INSENSITIVE]=1 ++ if (( rank > ihi_rank )); then ++ ibest_match=$path_field ++ ihi_rank=$rank ++ fi + fi + done + +@@ -707,6 +1263,10 @@ zshz() { + if [[ -n $best_match ]]; then + _zshz_output matches best_match $format + elif [[ -n $ibest_match ]]; then ++ # The winning match is the case-insensitive one; tell the ZSHZ_UNCOMMON ++ # trimmer to count case-insensitively. A case-sensitive winner (the branch ++ # above) correctly leaves the flag at the 0 set at the top of the search. ++ ZSHZ[CASE_INSENSITIVE]=1 + _zshz_output imatches ibest_match $format + fi + } +@@ -736,6 +1296,17 @@ zshz() { + return 1 + fi + ++ # -r (rank) and -t (recent) name different, mutually exclusive sort keys, so ++ # asking for both is contradictory. Reject it rather than letting an arbitrary ++ # one win -- the options loop below visits ${(k)opts} in hash order, so a ++ # silent winner would not even be predictable. Skipped when --complete is set: ++ # the completion widget always passes it, an error must not reach the terminal ++ # mid-completion, and the sort order is merely cosmetic for a completion list. ++ if (( ${+opts[-r]} && ${+opts[-t]} && ! ${+opts[--complete]} )); then ++ print "${ZSHZ_CMD:-${_Z_CMD:-z}}: options -r and -t cannot be combined." >&2 ++ return 1 ++ fi ++ + local opt output_format method='frecency' fnd prefix req + + for opt in ${(k)opts}; do +@@ -760,6 +1331,9 @@ zshz() { + ;; + --complete) + if [[ -s $datafile && ${ZSHZ_COMPLETION:-frecent} == 'legacy' ]]; then ++ lines=( ${(f)"$(< $datafile)"} ) ++ # Discard entries that are incomplete or incorrectly formatted ++ lines=( ${(M)lines:#/*\|[[:digit:]]##[.,]#[[:digit:]]#\|[[:digit:]]##} ) + _zshz_legacy_complete "$1" + return + fi +@@ -771,7 +1345,10 @@ zshz() { + _zshz_usage + return + ;; +- -l) output_format='list' ;; ++ # --complete (completion mode) always wins over -l, independent of the ++ # order ${(k)opts} happens to visit them: completing `z -l ...' must still ++ # emit bare paths for compadd, never the rank-padded rows of a list. ++ -l) (( ${+opts[--complete]} )) || output_format='list' ;; + -r) method='rank' ;; + -t) method='time' ;; + -x) +@@ -785,6 +1362,12 @@ zshz() { + ;; + esac + done ++ ++ # Load the datafile into an array and parse it ++ lines=( ${(f)"$(< $datafile)"} ) ++ # Discard entries that are incomplete or incorrectly formatted ++ lines=( ${(M)lines:#/*\|[[:digit:]]##[.,]#[[:digit:]]#\|[[:digit:]]##} ) ++ + req="$*" + fnd="$prefix$*" + +@@ -816,13 +1399,17 @@ zshz() { + # If $ZSHZ_ECHO == 1, display paths as you jump to them. + # If it is also the case that $ZSHZ_TILDE == 1, display + # the home directory as a tilde. ++ # ++ # Globals: ++ # ZSHZ_ECHO ++ # ZSHZ_TILDE + ######################################################### + _zshz_echo() { + if (( ZSHZ_ECHO )); then + if (( ZSHZ_TILDE )); then +- print ${PWD/#${HOME}/\~} ++ print -r -- ${PWD/#${HOME}/\~} + else +- print $PWD ++ print -r -- $PWD + fi + fi + } +@@ -832,11 +1419,88 @@ zshz() { + [[ -d ${@: -1} ]] && zshz_cd ${@: -1} && _zshz_echo && return + fi + +- # With option -c, make sure query string matches beginning of matches; +- # otherwise look for matches anywhere in paths ++ # Fast path: bare `zshz -l' (no query, list format). Skip the ++ # `_zshz_find_matches' / `_zshz_output' pipeline -- there is nothing ++ # to match against, no `matches[]'/`imatches[]' to maintain, no ++ # case-mode branching, no `${(Pkv)...}' copy. Build the formatted ++ # output array directly, then sort and print. Mirrors the list arm ++ # of `_zshz_output' but operates straight on $lines. ++ if [[ $output_format == 'list' && -z $fnd ]]; then ++ local line path_field rank_field time_field rank dx path_to_display dir ++ local common now=$EPOCHSECONDS ++ local -a output paths ++ local -i keep ++ ++ for line in $lines; do ++ path_field=${line%%\|*} ++ ++ if [[ ! -d $path_field ]]; then ++ keep=0 ++ for dir in ${(@)ZSHZ_KEEP_DIRS}; do ++ if [[ $path_field == ${dir}/* || $path_field == $dir || $dir == '/' ]]; then ++ keep=1 ++ break ++ fi ++ done ++ (( keep )) || continue ++ fi ++ ++ rank_field=${${line%\|*}#*\|} ++ time_field=${line##*\|} ++ case $method in ++ rank) rank=$rank_field ;; ++ time) (( rank = time_field - now )) ;; ++ *) ++ # Frecency routine -- see _zshz_find_matches for the canonical ++ # copy and the constants' rationale; keep the two in sync. ++ (( dx = now - time_field )) ++ rank=$(( 10000 * rank_field * (3.75/( (0.0001 * dx + 1) + 0.25)) )) ++ ;; ++ esac ++ (( rank )) || continue ++ ++ paths+=( $path_field ) ++ path_to_display=$path_field ++ (( ZSHZ_TILDE )) && path_to_display=${path_to_display/#${HOME}/\~} ++ # Conditional padding, never a bare `${(r:10:)}' -- see the list arm ++ # of `_zshz_output' for why a rank must not be truncated. ++ rank=${rank%.*} ++ (( ${#rank} < 10 )) && rank=${(r:10:)rank} ++ output+=( "$rank $path_to_display" ) ++ done ++ ++ if (( $#paths )); then ++ _zshz_find_common_root $paths ++ common=$REPLY ++ REPLY= ++ fi ++ ++ if [[ -n $common ]]; then ++ (( ZSHZ_TILDE )) && common=${common/#${HOME}/\~} ++ (( $#output > 1 )) && printf "%-10s %s\n" 'common:' $common ++ fi + +- # zpm-zsh/colors has a global $c, so we'll avoid math expressions here +- if [[ ! -z ${(tP)opts[-c]} ]]; then ++ if (( $#output )); then ++ if (( $+opts[-t] )); then ++ print -rl -- ${(@On)output} ++ else ++ print -rl -- ${(@on)output} ++ fi ++ return 0 ++ fi ++ return 1 ++ fi ++ ++ # With option -c, make sure query string matches beginning of matches; ++ # otherwise look for matches anywhere in paths. ++ # ++ # The `$PWD != /' guard mirrors the one where the prefix is set, above. At the ++ # root every path is already under $PWD, so no "$PWD " prefix is prepended and ++ # $fnd stays the bare query -- which, anchored, can never match a path ++ # beginning with `/'. Without the guard, `z -c foo' from `/' matches nothing ++ # whatever the query. Anchoring is still right in the other prefix-less case ++ # ($* is an absolute path under $PWD): there the query is itself anchored. ++ if (( ${+opts[-c]} )) && [[ $PWD != '/' ]]; then + _zshz_find_matches "$fnd*" $method $output_format + else + _zshz_find_matches "*$fnd*" $method $output_format +@@ -845,7 +1509,12 @@ zshz() { + local ret2=$? + + local cd +- cd=$REPLY ++ # Only the default (jump/echo) format communicates a destination through ++ # REPLY; list and completion print their results directly and leave REPLY ++ # empty. Checking the format here is a second line of defense: even if a ++ # future edit to `_zshz_output' lets a stray REPLY escape again, a listing ++ # must never turn into a directory change. ++ [[ -z $output_format ]] && cd=$REPLY + + # New experimental "uncommon" behavior + # +@@ -866,6 +1535,10 @@ zshz() { + # Try dropping directory elements from the right; stop when it affects + # how many times the search pattern appears + until (( ( ${#cd:h} - ${#${${cd:h}//${~q}/}} ) != q_chars )); do ++ # ${cd:h} of `/' is `/', so without this guard the trim could spin ++ # forever once it reaches the root (e.g. `/' in the database with a ++ # pattern that matches zero characters there). ++ [[ ${cd:h} == $cd ]] && break + cd=${cd:h} + done + +@@ -873,6 +1546,9 @@ zshz() { + else + local q_chars=$(( ${#cd} - ${#${${cd:l}//${~${q:l}}/}} )) + until (( ( ${#cd:h} - ${#${${${cd:h}:l}//${~${q:l}}/}} ) != q_chars )); do ++ # See the case-sensitive branch: guard against ${cd:h} no longer ++ # changing once the trim reaches the root. ++ [[ ${cd:h} == $cd ]] && break + cd=${cd:h} + done + fi +@@ -884,7 +1560,7 @@ zshz() { + if (( ret2 == 0 )) && [[ -n $cd ]]; then + if (( $+opts[-e] )); then # echo + (( ZSHZ_TILDE )) && cd=${cd/#${HOME}/\~} +- print -- "$cd" ++ print -r -- "$cd" + else + # cd if possible; echo the new path if $ZSHZ_ECHO == 1 + [[ -d $cd ]] && zshz_cd "$cd" && _zshz_echo +@@ -924,13 +1600,37 @@ _zshz_precmd() { + esac + done + +- # It appears that forking a subshell is so slow in Windows that it is better +- # just to add the PWD to the datafile in the foreground +- if [[ $OSTYPE == (cygwin|msys) ]]; then +- zshz --add "$PWD" +- else +- (zshz --add "$PWD" &) +- fi ++ # Add PWD to the datafile. Background the write so the prompt doesn't wait on ++ # read + tempfile + rename + chown -- which is tens of ms per prompt on ++ # 9P-bridged or VHD-backed paths. Backgrounding is safe under develop's ++ # lock design: the `always { zsystem flock -u $lockfd }' block in ++ # _zshz_add_or_remove_path guarantees the parent never holds an open ++ # lockfd between precmd invocations (so a `&!' fork can't inherit one), ++ # and ZSHZ_LOCK_TIMEOUT (default 1s) bounds contention so a stuck holder ++ # can't pile up writers. `&!' is zsh background + disown: no wrapper ++ # subshell, no job-table entry, no "Done" line at the next prompt. ++ # ++ # Do not restore the old foreground carve-out for Cygwin/MSYS2. It was ++ # right when backgrounding meant a subshell plus a job (two forks) and ++ # writes were line-by-line; with one disowned fork and batched writes, ++ # measurement (June 2026, Cygwin zsh 5.8 and MSYS2 zsh 5.9) shows ~10-12ms ++ # at the prompt for `&!' vs. ~30ms for a foreground add at 300 datafile ++ # entries -- and ~300ms at 1,000 entries, since the foreground cost grows ++ # with the datafile while the fork cost stays flat. ++ # ++ # `2> /dev/null' is what actually enforces the "stay quiet at every prompt" ++ # rule that $_zshz_quiet_add describes. That marker can only gate Zsh-z's own ++ # `print's; it cannot reach the external and builtin commands further down the ++ # --add path -- `mkdir -p', `id -ng', ${ZSHZ[CHOWN]}, the deliberately loud ++ # datafile-creation retry, or Zsh's own redirection diagnostics -- and any of ++ # those can fail when $ZSHZ_DATA sits on an unwritable or unmounted directory, ++ # or when $ZSHZ_OWNER names a user `id' can't resolve. Suppressing at the fork ++ # covers every such site at once, including ones added later, whereas ++ # suppressing site by site has to be kept in sync forever. Nothing actionable ++ # is lost: a foreground `z --add .' still reports in full, which is exactly ++ # the diagnostic the lock comment above tells the user to run. ++ local _zshz_quiet_add=1 ++ zshz --add "$PWD" 2> /dev/null &! + + # See https://github.com/rupa/z/pull/247/commits/081406117ea42ccb8d159f7630cfc7658db054b6 + : $RANDOM +@@ -961,11 +1661,33 @@ add-zsh-hook chpwd _zshz_chpwd + + # Standardized $0 handling + # https://zdharma-continuum.github.io/Zsh-100-Commits-Club/Zsh-Plugin-Standard.html +-0="${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}" ++0="${${ZERO:-${0:#${ZSH_ARGZERO-}}}:-${(%):-%N}}" + 0="${${(M)0:#/*}:-$PWD/$0}" + +-(( ${fpath[(ie)${0:A:h}]} <= ${#fpath} )) || fpath=( "${0:A:h}" "${fpath[@]}" ) ++# Capture the plugin directory while $0 still names this file: inside the ++# unload function, $0 is the function name (FUNCTION_ARGZERO), which `:A' ++# would resolve against $PWD. ++ZSHZ[PLUGIN_DIR]=${0:A:h} + ++# Add the plugin directory to $fpath only when nothing else has already put it ++# there, and record having done so, so that unload can take back this entry ++# and leave a plugin manager's alone. ++# ++# The record is only ever set, never cleared: on a re-source the directory is ++# already present -- because this file added it the first time -- and clearing ++# the record then would strand the entry in $fpath at unload. `typeset -gA' ++# above preserves the value across that re-source. ++if (( ${fpath[(ie)${ZSHZ[PLUGIN_DIR]}]} > ${#fpath} )); then ++ fpath=( "${ZSHZ[PLUGIN_DIR]}" "${fpath[@]}" ) ++ # Record the path itself, not a boolean. $ZSHZ[PLUGIN_DIR] is rewritten by ++ # every source, so a flag would end up describing whichever directory was ++ # sourced last: re-sourcing from a second, manager-owned installation would ++ # make unload drop *that* entry and strand the one this plugin actually ++ # added. Newline-separated, since a path may contain spaces, and split with ++ # `${(f)...}' at unload. ++ ZSHZ[ADDED_FPATH]="${ZSHZ[ADDED_FPATH]:+${ZSHZ[ADDED_FPATH]} ++}${ZSHZ[PLUGIN_DIR]}" ++fi + + # Save the existing Tab binding so that the completion widget can invoke it, + # but being careful not to create a situation where the widget ends up calling +@@ -992,6 +1714,24 @@ _zshz_zle_completion_widget() { + + local cmd=${ZSHZ_CMD:-${_Z_CMD:-z}} + ++ # Ensure tab completion works under `setopt COMPLETE_ALIASES'. Under that ++ # option zsh looks up `_comps[$cmd]' verbatim rather than expanding the ++ # alias to `zshz' first; compinit's static `#compdef' tag in `_zshz' is ++ # parsed literally (no parameter expansion) and only covers the literal ++ # `zshz' command. Run once -- the guard short-circuits on subsequent Tabs. ++ # Record what was registered, so `zsh-z_plugin_unload' can take back exactly ++ # this entry and nothing else. Keyed on the effect rather than compdef's exit ++ # status: if the mapping did not land, there is nothing to take back. ++ if (( ! ${+_comps[$cmd]} )); then ++ compdef _zshz $cmd 2> /dev/null ++ # Append rather than overwrite. Re-sourcing with a changed $ZSHZ_CMD ++ # registers a second command while the first mapping is still live, and a ++ # single slot would forget the earlier one and strand it at unload. Space- ++ # separated, like $ZSHZ[FUNCTIONS], and split with `${=...}' there. ++ [[ ${_comps[$cmd]-} == '_zshz' ]] && ++ ZSHZ[COMPDEF]="${ZSHZ[COMPDEF]:+${ZSHZ[COMPDEF]} }$cmd" ++ fi ++ + # If a trailing space was added after an already-completed absolute path + # (e.g. `z /usr/local/bin '), a second Tab would otherwise re-trigger + # completion on an empty word and insert a duplicate. Bail out early. +@@ -1039,13 +1779,15 @@ fi + # zsh-z functions + ############################################################ + ZSHZ[FUNCTIONS]='_zshz_usage ++ _zshz_realpath + _zshz_add_or_remove_path + _zshz_update_datafile + _zshz_legacy_complete +- _zshz_printv + _zshz_find_common_root + _zshz_output + _zshz_find_matches ++ zshz_cd ++ _zshz_echo + zshz + _zshz_precmd + _zshz_chpwd +@@ -1095,9 +1837,49 @@ zsh-z_plugin_unload() { + (( ${+functions[$x]} )) && unfunction $x + done + +- unset ZSHZ ++ # The directory captured at source time -- $0 here is the function name, ++ # not the plugin file. Read it before ZSHZ is unset. ++ # ++ # Only when this plugin was the one that added it. A plugin manager that put ++ # the directory on $fpath owns that entry: taking it away would break ++ # autoloads for anything else living there and leave the manager believing ++ # its configuration is intact. And drop a single occurrence rather than ++ # filtering every match -- at most one of any duplicates can be ours. ++ # ++ # `(ie)', not `(i)': without the `e' the subscript treats the stored path as ++ # a *pattern*, so a plugin directory containing `[', `*' or `?' would not ++ # match itself and the entry would be left behind. The source-time lookup ++ # already uses `(ie)'; these two must agree. ++ local _zshz_dir ++ integer _zshz_fp ++ for _zshz_dir in ${(f)ZSHZ[ADDED_FPATH]-}; do ++ [[ -n $_zshz_dir ]] || continue ++ _zshz_fp=${fpath[(ie)$_zshz_dir]} ++ (( _zshz_fp <= ${#fpath} )) && fpath[$_zshz_fp]=() ++ done ++ ++ # Take back the completion mapping the widget installed on its first Tab. ++ # Without this the entry outlives the function it names -- `_zshz' is ++ # unfunctioned above and the plugin directory has just left $fpath, so a ++ # later completion on that command looks up something unloadable. ++ # ++ # Only this one entry. compinit's own registrations (`_comps[zshz]', from the ++ # static `#compdef' tag) are deliberately left in place: nothing re-runs ++ # compinit when the plugin is sourced again, so removing them would break ++ # completion for the literal `zshz' command until the user re-ran it by hand. ++ # This entry has no such problem -- the widget re-registers it on the next ++ # Tab after a reload. ++ # ++ # `$ZSHZ[COMPDEF]' is the ownership record: the registration above never ++ # overwrites an existing mapping, so one Zsh-z did not create must survive ++ # unload. Re-check the value too, in case it was repointed since. ++ local _zshz_compdef ++ for _zshz_compdef in ${=ZSHZ[COMPDEF]-}; do ++ [[ ${_comps[$_zshz_compdef]-} == '_zshz' ]] && ++ compdef -d "$_zshz_compdef" 2> /dev/null ++ done + +- fpath=( "${(@)fpath:#${0:A:h}}" ) ++ unset ZSHZ + + (( ${+aliases[${ZSHZ_CMD:-${_Z_CMD:-z}}]} )) && + unalias ${ZSHZ_CMD:-${_Z_CMD:-z}} diff --git a/tasks/ohmyzsh__ohmyzsh-13957/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-13957/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8490ebacda3bba810908ae3e3aa9430afaaa94eb --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13957/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b54a71977574cfcf659cc2f15a5e6422f17a8da7 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-13957/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-13957/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13957/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-13960/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-13960/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5ab936088be9150cf324c8f13f0dde7758d61cfe --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13960/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b54a71977574cfcf659cc2f15a5e6422f17a8da7 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b54a71977574cfcf659cc2f15a5e6422f17a8da7 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b54a71977574cfcf659cc2f15a5e6422f17a8da7 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-13960/instruction.md b/tasks/ohmyzsh__ohmyzsh-13960/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fd21efe886cba1da35042c558166acb300187a37 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13960/instruction.md @@ -0,0 +1,46 @@ +# Issue + +**Title:** fix(install): prevent command injection via \ in install.sh + +## Description + +## Problem + +`tools/install.sh` runs an `eval` on a value derived from the environment: + +```sh +HOME="${HOME:-$(getent passwd $USER 2>/dev/null | cut -d: -f6)}" +# macOS does not have getent, but this works even if $HOME is unset +HOME="${HOME:-$(eval echo ~"$USER")}" +``` + +When `HOME` is unset (e.g. containers, minimal environments), `eval echo ~"$USER"` expands any shell metacharacters in `$USER` (CWE-78). A crafted `USER` like `x"; touch /tmp/pwned; "` executes the embedded command. The script is normally run via `curl | sh`, so the environment is attacker-influencable in some setups. + +Additionally, `getent passwd $USER` is unquoted (word splitting). + +## Fix + +Validate the username against a safe character set before the `eval`, falling back to `$PWD` for unsafe/empty values, and quote `$USER` in the `getent` call: + +```sh +HOME="${HOME:-$(getent passwd "$USER" 2>/dev/null | cut -d: -f6)}" +case "$USER" in + *[![:alnum:]_.-]*|'') + HOME="${HOME:-$PWD}" + ;; + *) + HOME="${HOME:-$(eval echo ~"$USER")}" + ;; +esac +``` + +Behavior for normal usernames is unchanged (tilde expansion still applies); only unsafe `$USER` values are short-circuited. + +## Tests + +- `bash -n tools/install.sh` passes. +- Functional tests in bash: malicious `USER='x"; touch /tmp/pwned; "'` → no file created, `HOME` falls back to `$PWD`; `USER=root` → `HOME=/root`; `USER=john.doe-test` (valid chars) → unchanged behavior; empty `USER` → `$PWD`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b54a71977574`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13960/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-13960/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..35d1a19e6b44d960d694f9291328491c0be1250d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13960/solution/patch.diff @@ -0,0 +1,39 @@ +diff --git a/tools/install.sh b/tools/install.sh +index 3eae21f9..55207536 100755 +--- a/tools/install.sh ++++ b/tools/install.sh +@@ -49,9 +49,31 @@ USER=${USER:-$(id -u -n)} + # $HOME is defined at the time of login, but it could be unset. If it is unset, + # a tilde by itself (~) will not be expanded to the current user's home directory. + # POSIX: https://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap08.html#tag_08_03 +-HOME="${HOME:-$(getent passwd $USER 2>/dev/null | cut -d: -f6)}" +-# macOS does not have getent, but this works even if $HOME is unset +-HOME="${HOME:-$(eval echo ~"$USER")}" ++if [ -z "$HOME" ]; then ++ HOME=$(getent passwd "$USER" 2>/dev/null | cut -d: -f6) ++ ++ # macOS does not have getent; fall back to tilde expansion, but only if ++ # $USER is a safe username. The eval below would otherwise expand any shell ++ # metacharacters in $USER and allow command injection (CWE-78). ++ case "$USER" in ++ *[![:alnum:]_.-]*|'') ++ ;; ++ *) ++ resolved_home=$(eval echo ~"$USER") ++ # Unknown users are not expanded and produce a literal "~username". ++ [ "$resolved_home" = "~$USER" ] || HOME=$resolved_home ++ ;; ++ esac ++ ++ case "$HOME" in ++ /*) ;; ++ *) ++ echo "Error: unable to determine the current user's home directory." >&2 ++ echo "Set HOME explicitly and rerun the installer." >&2 ++ exit 1 ++ ;; ++ esac ++fi + + + # Track if $ZSH was provided diff --git a/tasks/ohmyzsh__ohmyzsh-13960/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-13960/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13960/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-13960/task.toml b/tasks/ohmyzsh__ohmyzsh-13960/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..987a63292738730e1440c6432a907f1185a01037 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13960/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-13960" +description = "fix(install): prevent command injection via \\ in install.sh" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "b54a71977574cfcf659cc2f15a5e6422f17a8da7" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/13960" +source_access = "auto" +built_at = "2026-11-16T16:09:57.024297+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1e4dd5937ed916e79db068ec76557a98b14ac1475a9c2c64e99b77a12ea90811" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-20T08:43:08Z" +diff_format = "unified" +context_files = [ + "tools/install.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 28 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.961224+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:48c104d5c7ac1aa7732448d20b936b78e49d8b4fcac90871610c967eecb978fc" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-13960/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-13960/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13960/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-13960/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-13960/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fd21efe886cba1da35042c558166acb300187a37 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13960/tests/instruction.md @@ -0,0 +1,46 @@ +# Issue + +**Title:** fix(install): prevent command injection via \ in install.sh + +## Description + +## Problem + +`tools/install.sh` runs an `eval` on a value derived from the environment: + +```sh +HOME="${HOME:-$(getent passwd $USER 2>/dev/null | cut -d: -f6)}" +# macOS does not have getent, but this works even if $HOME is unset +HOME="${HOME:-$(eval echo ~"$USER")}" +``` + +When `HOME` is unset (e.g. containers, minimal environments), `eval echo ~"$USER"` expands any shell metacharacters in `$USER` (CWE-78). A crafted `USER` like `x"; touch /tmp/pwned; "` executes the embedded command. The script is normally run via `curl | sh`, so the environment is attacker-influencable in some setups. + +Additionally, `getent passwd $USER` is unquoted (word splitting). + +## Fix + +Validate the username against a safe character set before the `eval`, falling back to `$PWD` for unsafe/empty values, and quote `$USER` in the `getent` call: + +```sh +HOME="${HOME:-$(getent passwd "$USER" 2>/dev/null | cut -d: -f6)}" +case "$USER" in + *[![:alnum:]_.-]*|'') + HOME="${HOME:-$PWD}" + ;; + *) + HOME="${HOME:-$(eval echo ~"$USER")}" + ;; +esac +``` + +Behavior for normal usernames is unchanged (tilde expansion still applies); only unsafe `$USER` values are short-circuited. + +## Tests + +- `bash -n tools/install.sh` passes. +- Functional tests in bash: malicious `USER='x"; touch /tmp/pwned; "'` → no file created, `HOME` falls back to `$PWD`; `USER=root` → `HOME=/root`; `USER=john.doe-test` (valid chars) → unchanged behavior; empty `USER` → `$PWD`. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b54a71977574`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13960/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-13960/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..35d1a19e6b44d960d694f9291328491c0be1250d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13960/tests/oracle.patch @@ -0,0 +1,39 @@ +diff --git a/tools/install.sh b/tools/install.sh +index 3eae21f9..55207536 100755 +--- a/tools/install.sh ++++ b/tools/install.sh +@@ -49,9 +49,31 @@ USER=${USER:-$(id -u -n)} + # $HOME is defined at the time of login, but it could be unset. If it is unset, + # a tilde by itself (~) will not be expanded to the current user's home directory. + # POSIX: https://pubs.opengroup.org/onlinepubs/009696899/basedefs/xbd_chap08.html#tag_08_03 +-HOME="${HOME:-$(getent passwd $USER 2>/dev/null | cut -d: -f6)}" +-# macOS does not have getent, but this works even if $HOME is unset +-HOME="${HOME:-$(eval echo ~"$USER")}" ++if [ -z "$HOME" ]; then ++ HOME=$(getent passwd "$USER" 2>/dev/null | cut -d: -f6) ++ ++ # macOS does not have getent; fall back to tilde expansion, but only if ++ # $USER is a safe username. The eval below would otherwise expand any shell ++ # metacharacters in $USER and allow command injection (CWE-78). ++ case "$USER" in ++ *[![:alnum:]_.-]*|'') ++ ;; ++ *) ++ resolved_home=$(eval echo ~"$USER") ++ # Unknown users are not expanded and produce a literal "~username". ++ [ "$resolved_home" = "~$USER" ] || HOME=$resolved_home ++ ;; ++ esac ++ ++ case "$HOME" in ++ /*) ;; ++ *) ++ echo "Error: unable to determine the current user's home directory." >&2 ++ echo "Set HOME explicitly and rerun the installer." >&2 ++ exit 1 ++ ;; ++ esac ++fi + + + # Track if $ZSH was provided diff --git a/tasks/ohmyzsh__ohmyzsh-13960/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-13960/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8490ebacda3bba810908ae3e3aa9430afaaa94eb --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13960/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b54a71977574cfcf659cc2f15a5e6422f17a8da7 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-13960/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-13960/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13960/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-13961/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-13961/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f6454b982fc90326f646b382301eabe6bd9d3e65 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13961/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 97e11051e2f8053b1d694788d1cb4b0dbb1e2365 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 97e11051e2f8053b1d694788d1cb4b0dbb1e2365 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 97e11051e2f8053b1d694788d1cb4b0dbb1e2365 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-13961/instruction.md b/tasks/ohmyzsh__ohmyzsh-13961/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ccc79d1128807094aeda81d30274324bf14b6e05 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13961/instruction.md @@ -0,0 +1,37 @@ +# Issue + +**Title:** fix(core): add Ghostty OSC 8 support + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Recognize Ghostty's `TERM_PROGRAM=ghostty` and `TERM=xterm-ghostty` identifiers. +- Enable OSC 8 hyperlinks in the changelog, updater, and installer when running in Ghostty. +- Keep the terminal identifier lists alphabetized. + +## Other comments: + +This extends the existing changelog hyperlink support from . + +Tested manually in Ghostty by running `tools/changelog.sh` directly and command-clicking commit and PR links successfully. All modified scripts pass `zsh -n`. + +The scope is intentionally limited to Ghostty. + +AI-assisted: Codex helped investigate, implement, and test this change; I reviewed the resulting diff. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `97e11051e2f8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13961/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-13961/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..28316e27baa1282d717eacc37664eda8bcf8f9fe --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13961/solution/patch.diff @@ -0,0 +1,57 @@ +diff --git a/tools/changelog.sh b/tools/changelog.sh +index ff409115..2466744d 100755 +--- a/tools/changelog.sh ++++ b/tools/changelog.sh +@@ -221,12 +221,12 @@ supports_hyperlinks() { + + # If $TERM_PROGRAM is set, these terminals support hyperlinks + case "$TERM_PROGRAM" in +- Hyper|iTerm.app|terminology|WezTerm|vscode) return 0 ;; ++ ghostty|Hyper|iTerm.app|terminology|vscode|WezTerm) return 0 ;; + esac + + # These termcap entries support hyperlinks + case "$TERM" in +- xterm-kitty|alacritty|alacritty-direct) return 0 ;; ++ alacritty|alacritty-direct|xterm-ghostty|xterm-kitty) return 0 ;; + esac + + # xfce4-terminal supports hyperlinks +diff --git a/tools/install.sh b/tools/install.sh +index 3eae21f9..0af9fada 100755 +--- a/tools/install.sh ++++ b/tools/install.sh +@@ -168,12 +168,12 @@ supports_hyperlinks() { + + # If $TERM_PROGRAM is set, these terminals support hyperlinks + case "$TERM_PROGRAM" in +- Hyper|iTerm.app|terminology|WezTerm|vscode) return 0 ;; ++ ghostty|Hyper|iTerm.app|terminology|vscode|WezTerm) return 0 ;; + esac + + # These termcap entries support hyperlinks + case "$TERM" in +- xterm-kitty|alacritty|alacritty-direct) return 0 ;; ++ alacritty|alacritty-direct|xterm-ghostty|xterm-kitty) return 0 ;; + esac + + # xfce4-terminal supports hyperlinks +diff --git a/tools/upgrade.sh b/tools/upgrade.sh +index 01719d21..df8d0f34 100755 +--- a/tools/upgrade.sh ++++ b/tools/upgrade.sh +@@ -95,12 +95,12 @@ supports_hyperlinks() { + + # If $TERM_PROGRAM is set, these terminals support hyperlinks + case "$TERM_PROGRAM" in +- Hyper|iTerm.app|terminology|WezTerm|vscode) return 0 ;; ++ ghostty|Hyper|iTerm.app|terminology|vscode|WezTerm) return 0 ;; + esac + + # These termcap entries support hyperlinks + case "$TERM" in +- xterm-kitty|alacritty|alacritty-direct) return 0 ;; ++ alacritty|alacritty-direct|xterm-ghostty|xterm-kitty) return 0 ;; + esac + + # xfce4-terminal supports hyperlinks diff --git a/tasks/ohmyzsh__ohmyzsh-13961/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-13961/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13961/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-13961/task.toml b/tasks/ohmyzsh__ohmyzsh-13961/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..45d220b103705a94d29ad10b4a2d1e6f8fe2d109 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13961/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-13961" +description = "fix(core): add Ghostty OSC 8 support" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "97e11051e2f8053b1d694788d1cb4b0dbb1e2365" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/13961" +source_access = "auto" +built_at = "2026-11-16T16:09:57.025982+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b233e18fc6f60d1a0e291f073a5c95e98c63fb8dce0b4bf45fd9a9f4337756d3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-20T08:18:07Z" +diff_format = "unified" +context_files = [ + "tools/changelog.sh", + "tools/install.sh", + "tools/upgrade.sh", +] +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.961763+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:5c216b27a65ae7c90db1c2f81ba12777910d421bb7fb24340bce0b44093143db" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-13961/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-13961/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13961/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-13961/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-13961/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ccc79d1128807094aeda81d30274324bf14b6e05 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13961/tests/instruction.md @@ -0,0 +1,37 @@ +# Issue + +**Title:** fix(core): add Ghostty OSC 8 support + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Recognize Ghostty's `TERM_PROGRAM=ghostty` and `TERM=xterm-ghostty` identifiers. +- Enable OSC 8 hyperlinks in the changelog, updater, and installer when running in Ghostty. +- Keep the terminal identifier lists alphabetized. + +## Other comments: + +This extends the existing changelog hyperlink support from . + +Tested manually in Ghostty by running `tools/changelog.sh` directly and command-clicking commit and PR links successfully. All modified scripts pass `zsh -n`. + +The scope is intentionally limited to Ghostty. + +AI-assisted: Codex helped investigate, implement, and test this change; I reviewed the resulting diff. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `97e11051e2f8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13961/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-13961/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..28316e27baa1282d717eacc37664eda8bcf8f9fe --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13961/tests/oracle.patch @@ -0,0 +1,57 @@ +diff --git a/tools/changelog.sh b/tools/changelog.sh +index ff409115..2466744d 100755 +--- a/tools/changelog.sh ++++ b/tools/changelog.sh +@@ -221,12 +221,12 @@ supports_hyperlinks() { + + # If $TERM_PROGRAM is set, these terminals support hyperlinks + case "$TERM_PROGRAM" in +- Hyper|iTerm.app|terminology|WezTerm|vscode) return 0 ;; ++ ghostty|Hyper|iTerm.app|terminology|vscode|WezTerm) return 0 ;; + esac + + # These termcap entries support hyperlinks + case "$TERM" in +- xterm-kitty|alacritty|alacritty-direct) return 0 ;; ++ alacritty|alacritty-direct|xterm-ghostty|xterm-kitty) return 0 ;; + esac + + # xfce4-terminal supports hyperlinks +diff --git a/tools/install.sh b/tools/install.sh +index 3eae21f9..0af9fada 100755 +--- a/tools/install.sh ++++ b/tools/install.sh +@@ -168,12 +168,12 @@ supports_hyperlinks() { + + # If $TERM_PROGRAM is set, these terminals support hyperlinks + case "$TERM_PROGRAM" in +- Hyper|iTerm.app|terminology|WezTerm|vscode) return 0 ;; ++ ghostty|Hyper|iTerm.app|terminology|vscode|WezTerm) return 0 ;; + esac + + # These termcap entries support hyperlinks + case "$TERM" in +- xterm-kitty|alacritty|alacritty-direct) return 0 ;; ++ alacritty|alacritty-direct|xterm-ghostty|xterm-kitty) return 0 ;; + esac + + # xfce4-terminal supports hyperlinks +diff --git a/tools/upgrade.sh b/tools/upgrade.sh +index 01719d21..df8d0f34 100755 +--- a/tools/upgrade.sh ++++ b/tools/upgrade.sh +@@ -95,12 +95,12 @@ supports_hyperlinks() { + + # If $TERM_PROGRAM is set, these terminals support hyperlinks + case "$TERM_PROGRAM" in +- Hyper|iTerm.app|terminology|WezTerm|vscode) return 0 ;; ++ ghostty|Hyper|iTerm.app|terminology|vscode|WezTerm) return 0 ;; + esac + + # These termcap entries support hyperlinks + case "$TERM" in +- xterm-kitty|alacritty|alacritty-direct) return 0 ;; ++ alacritty|alacritty-direct|xterm-ghostty|xterm-kitty) return 0 ;; + esac + + # xfce4-terminal supports hyperlinks diff --git a/tasks/ohmyzsh__ohmyzsh-13961/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-13961/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..898f3c8025189b491907eaca78e3d24f7efb2296 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13961/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 97e11051e2f8053b1d694788d1cb4b0dbb1e2365 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-13961/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-13961/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13961/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-13962/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-13962/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..852f80232204a863242d17fcaf4a36af927432b9 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13962/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 593e8ed6c8b4686654e1ff059d1e8e345082c848 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 593e8ed6c8b4686654e1ff059d1e8e345082c848 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 593e8ed6c8b4686654e1ff059d1e8e345082c848 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-13962/instruction.md b/tasks/ohmyzsh__ohmyzsh-13962/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ac2ee6ed0886d737d90c7d43ae6b1485f7cb770c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13962/instruction.md @@ -0,0 +1,80 @@ +# Issue + +**Title:** feat(jj): add common command aliases + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +Add commonly used aliases for core jj commands and subcommands: + +- `jjblt` → `jj bookmark list --tracked` +- `jjcfg` → `jj config` +- `jjcfgl` → `jj config list` +- `jjdst` → `jj diff --stat` +- `jjev` → `jj evolog` +- `jjf` → `jj file` +- `jjfl` → `jj file list` +- `jjg` → `jj git` +- `jjgi` → `jj git init` +- `jjgrl` → `jj git remote list` +- `jjop` → `jj op` +- `jjopl` → `jj op log` +- `jjor` → `jj op restore` +- `jjs` → `jj show` +- `jju` → `jj undo` +- `jjw` → `jj workspace` +- `jjwl` → `jj workspace list` + +The README also documents the previously added `jjwa` and `jjwf` aliases. + +These aliases provide short, consistent access to commands that are useful during normal jj workflows: + +- Inspecting changes with `jjs`, `jjdst`, and `jjf`/`jjfl` +- Reviewing tracked bookmarks and configuration with `jjblt`, `jjcfg`, and `jjcfgl` +- Working with Git repositories and remotes using `jjg`, `jjgi`, and `jjgrl` +- Inspecting and recovering operations with `jjev`, `jjop`, `jjopl`, `jjor`, and `jju` +- Managing workspaces with `jjw`, `jjwl`, `jjwa`, and `jjwf` + +The new aliases copy existing compositional conventions for symmetry. For example, the existing `jjb` maps to `jj bookmark`, while `jjbl` maps to `jj bookmark list`. This change applies the same pattern to `jjg`/`jjgf`, `jjw`/`jjwl`, and `jjop`/`jjopl` for Git, workspace, and operation commands. + +This makes the aliases easier to remember without needing to recall which underlying jj commands use spaces or built-in command aliases. + +## Other comments: + +Review from previous jj plugin contributors would be especially valuable: + +- [@nasso](https://github.com/nasso), the original jj plugin author, introduced the plugin in . +- [@imp](https://github.com/imp), who contributed several earlier jj aliases in and . +- [@danvratil](https://github.com/danvratil), who added the existing workspace aliases in . +- [@laurensrouw](https://github.com/laurensrouw), who added the existing bookmark alias in . + +[@martinvonz](https://github.com/martinvonz) may also be a useful reviewer for checking that the selected aliases match common jj usage and terminology, given the discussion in . + +Validation performed: + +- `zsh -n plugins/jj/jj.plugin.zsh` +- Sourced the plugin and verified the new alias expansions +- Checked the relevant jj command help output +- Verified that every plugin alias is documented in the README +- Reviewed the resulting jj diff + +AI-assisted: Codex helped draft and apply the alias and README changes and run validation. I reviewed the resulting diff and manually verified the aliases and command targets. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `593e8ed6c8b4`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13962/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-13962/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..79dfae25aa173e4c3b7a762286251aa320550fa1 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13962/solution/patch.diff @@ -0,0 +1,115 @@ +diff --git a/plugins/jj/README.md b/plugins/jj/README.md +index c70e0558..c9e490ed 100644 +--- a/plugins/jj/README.md ++++ b/plugins/jj/README.md +@@ -19,35 +19,54 @@ plugins=(... jj) + | jjbd | `jj bookmark delete` | + | jjbf | `jj bookmark forget` | + | jjbl | `jj bookmark list` | ++| jjblt | `jj bookmark list --tracked` | + | jjbm | `jj bookmark move` | + | jjbr | `jj bookmark rename` | + | jjbs | `jj bookmark set` | + | jjbt | `jj bookmark track` | + | jjbu | `jj bookmark untrack` | + | jjc | `jj commit` | ++| jjcfg | `jj config` | ++| jjcfgl | `jj config list` | + | jjcmsg | `jj commit --message` | + | jjd | `jj diff` | + | jjdmsg | `jj desc --message` | + | jjds | `jj desc` | ++| jjdst | `jj diff --stat` | + | jje | `jj edit` | ++| jjev | `jj evolog` | ++| jjf | `jj file` | ++| jjfl | `jj file list` | ++| jjg | `jj git` | + | jjgcl | `jj git clone` | + | jjgf | `jj git fetch` | + | jjgfa | `jj git fetch --all-remotes` | ++| jjgi | `jj git init` | + | jjgp | `jj git push` | + | jjgpa | `jj git push --all` | + | jjgpd | `jj git push --deleted` | + | jjgpt | `jj git push --tracked` | ++| jjgrl | `jj git remote list` | + | jjl | `jj log` | + | jjla | `jj log -r "all()"` | + | jjn | `jj new` | + | jjnt | `jj new "trunk()"` | ++| jjop | `jj op` | ++| jjopl | `jj op log` | ++| jjor | `jj op restore` | + | jjrb | `jj rebase` | + | jjrbm | `jj rebase -d "trunk()"` | + | jjrs | `jj restore` | + | jjrt | `cd "$(jj root \|\| echo .)"` | ++| jjs | `jj show` | + | jjsp | `jj split` | + | jjsq | `jj squash` | + | jjst | `jj status` | ++| jju | `jj undo` | ++| jjw | `jj workspace` | ++| jjwa | `jj workspace add` | ++| jjwf | `jj workspace forget` | ++| jjwl | `jj workspace list` | + + ## Prompt usage + +diff --git a/plugins/jj/jj.plugin.zsh b/plugins/jj/jj.plugin.zsh +index db0d3e8f..90b8d7b0 100644 +--- a/plugins/jj/jj.plugin.zsh ++++ b/plugins/jj/jj.plugin.zsh +@@ -45,34 +45,51 @@ alias jjbc='jj bookmark create' + alias jjbd='jj bookmark delete' + alias jjbf='jj bookmark forget' + alias jjbl='jj bookmark list' ++alias jjblt='jj bookmark list --tracked' + alias jjbm='jj bookmark move' + alias jjbr='jj bookmark rename' + alias jjbs='jj bookmark set' + alias jjbt='jj bookmark track' + alias jjbu='jj bookmark untrack' + alias jjc='jj commit' ++alias jjcfg='jj config' ++alias jjcfgl='jj config list' + alias jjcmsg='jj commit --message' + alias jjd='jj diff' + alias jjdmsg='jj desc --message' + alias jjds='jj desc' ++alias jjdst='jj diff --stat' + alias jje='jj edit' ++alias jjev='jj evolog' ++alias jjf='jj file' ++alias jjfl='jj file list' ++alias jjg='jj git' + alias jjgcl='jj git clone' + alias jjgf='jj git fetch' + alias jjgfa='jj git fetch --all-remotes' ++alias jjgi='jj git init' + alias jjgp='jj git push' + alias jjgpa='jj git push --all' + alias jjgpd='jj git push --deleted' + alias jjgpt='jj git push --tracked' ++alias jjgrl='jj git remote list' + alias jjl='jj log' + alias jjla='jj log -r "all()"' + alias jjn='jj new' + alias jjnt='jj new "trunk()"' ++alias jjop='jj op' ++alias jjopl='jj op log' ++alias jjor='jj op restore' + alias jjrb='jj rebase' + alias jjrbm='jj rebase -d "trunk()"' + alias jjrs='jj restore' + alias jjrt='cd "$(jj root || echo .)"' ++alias jjs='jj show' + alias jjsp='jj split' + alias jjsq='jj squash' + alias jjst='jj status' ++alias jju='jj undo' ++alias jjw='jj workspace' + alias jjwa='jj workspace add' + alias jjwf='jj workspace forget' ++alias jjwl='jj workspace list' diff --git a/tasks/ohmyzsh__ohmyzsh-13962/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-13962/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13962/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-13962/task.toml b/tasks/ohmyzsh__ohmyzsh-13962/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2b5d8f380b5df2aa9eb6a9f32b1cf65ff5e9c512 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13962/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-13962" +description = "feat(jj): add common command aliases" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "593e8ed6c8b4686654e1ff059d1e8e345082c848" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/13962" +source_access = "auto" +built_at = "2026-11-16T16:09:56.999292+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:61b04d0d9af3c33c26018fe981276ae5fee5b2d05cc15f090ef1ee0409383b5b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-05T21:36:15Z" +diff_format = "unified" +context_files = [ + "plugins/jj/README.md", + "plugins/jj/jj.plugin.zsh", +] +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.962254+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6eb5e8a9e578c1874a7b5fac41fbb656272ae5171f8eacc15f009f30c7cf74db" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-13962/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-13962/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13962/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-13962/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-13962/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ac2ee6ed0886d737d90c7d43ae6b1485f7cb770c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13962/tests/instruction.md @@ -0,0 +1,80 @@ +# Issue + +**Title:** feat(jj): add common command aliases + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +Add commonly used aliases for core jj commands and subcommands: + +- `jjblt` → `jj bookmark list --tracked` +- `jjcfg` → `jj config` +- `jjcfgl` → `jj config list` +- `jjdst` → `jj diff --stat` +- `jjev` → `jj evolog` +- `jjf` → `jj file` +- `jjfl` → `jj file list` +- `jjg` → `jj git` +- `jjgi` → `jj git init` +- `jjgrl` → `jj git remote list` +- `jjop` → `jj op` +- `jjopl` → `jj op log` +- `jjor` → `jj op restore` +- `jjs` → `jj show` +- `jju` → `jj undo` +- `jjw` → `jj workspace` +- `jjwl` → `jj workspace list` + +The README also documents the previously added `jjwa` and `jjwf` aliases. + +These aliases provide short, consistent access to commands that are useful during normal jj workflows: + +- Inspecting changes with `jjs`, `jjdst`, and `jjf`/`jjfl` +- Reviewing tracked bookmarks and configuration with `jjblt`, `jjcfg`, and `jjcfgl` +- Working with Git repositories and remotes using `jjg`, `jjgi`, and `jjgrl` +- Inspecting and recovering operations with `jjev`, `jjop`, `jjopl`, `jjor`, and `jju` +- Managing workspaces with `jjw`, `jjwl`, `jjwa`, and `jjwf` + +The new aliases copy existing compositional conventions for symmetry. For example, the existing `jjb` maps to `jj bookmark`, while `jjbl` maps to `jj bookmark list`. This change applies the same pattern to `jjg`/`jjgf`, `jjw`/`jjwl`, and `jjop`/`jjopl` for Git, workspace, and operation commands. + +This makes the aliases easier to remember without needing to recall which underlying jj commands use spaces or built-in command aliases. + +## Other comments: + +Review from previous jj plugin contributors would be especially valuable: + +- [@nasso](https://github.com/nasso), the original jj plugin author, introduced the plugin in . +- [@imp](https://github.com/imp), who contributed several earlier jj aliases in and . +- [@danvratil](https://github.com/danvratil), who added the existing workspace aliases in . +- [@laurensrouw](https://github.com/laurensrouw), who added the existing bookmark alias in . + +[@martinvonz](https://github.com/martinvonz) may also be a useful reviewer for checking that the selected aliases match common jj usage and terminology, given the discussion in . + +Validation performed: + +- `zsh -n plugins/jj/jj.plugin.zsh` +- Sourced the plugin and verified the new alias expansions +- Checked the relevant jj command help output +- Verified that every plugin alias is documented in the README +- Reviewed the resulting jj diff + +AI-assisted: Codex helped draft and apply the alias and README changes and run validation. I reviewed the resulting diff and manually verified the aliases and command targets. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `593e8ed6c8b4`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13962/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-13962/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..79dfae25aa173e4c3b7a762286251aa320550fa1 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13962/tests/oracle.patch @@ -0,0 +1,115 @@ +diff --git a/plugins/jj/README.md b/plugins/jj/README.md +index c70e0558..c9e490ed 100644 +--- a/plugins/jj/README.md ++++ b/plugins/jj/README.md +@@ -19,35 +19,54 @@ plugins=(... jj) + | jjbd | `jj bookmark delete` | + | jjbf | `jj bookmark forget` | + | jjbl | `jj bookmark list` | ++| jjblt | `jj bookmark list --tracked` | + | jjbm | `jj bookmark move` | + | jjbr | `jj bookmark rename` | + | jjbs | `jj bookmark set` | + | jjbt | `jj bookmark track` | + | jjbu | `jj bookmark untrack` | + | jjc | `jj commit` | ++| jjcfg | `jj config` | ++| jjcfgl | `jj config list` | + | jjcmsg | `jj commit --message` | + | jjd | `jj diff` | + | jjdmsg | `jj desc --message` | + | jjds | `jj desc` | ++| jjdst | `jj diff --stat` | + | jje | `jj edit` | ++| jjev | `jj evolog` | ++| jjf | `jj file` | ++| jjfl | `jj file list` | ++| jjg | `jj git` | + | jjgcl | `jj git clone` | + | jjgf | `jj git fetch` | + | jjgfa | `jj git fetch --all-remotes` | ++| jjgi | `jj git init` | + | jjgp | `jj git push` | + | jjgpa | `jj git push --all` | + | jjgpd | `jj git push --deleted` | + | jjgpt | `jj git push --tracked` | ++| jjgrl | `jj git remote list` | + | jjl | `jj log` | + | jjla | `jj log -r "all()"` | + | jjn | `jj new` | + | jjnt | `jj new "trunk()"` | ++| jjop | `jj op` | ++| jjopl | `jj op log` | ++| jjor | `jj op restore` | + | jjrb | `jj rebase` | + | jjrbm | `jj rebase -d "trunk()"` | + | jjrs | `jj restore` | + | jjrt | `cd "$(jj root \|\| echo .)"` | ++| jjs | `jj show` | + | jjsp | `jj split` | + | jjsq | `jj squash` | + | jjst | `jj status` | ++| jju | `jj undo` | ++| jjw | `jj workspace` | ++| jjwa | `jj workspace add` | ++| jjwf | `jj workspace forget` | ++| jjwl | `jj workspace list` | + + ## Prompt usage + +diff --git a/plugins/jj/jj.plugin.zsh b/plugins/jj/jj.plugin.zsh +index db0d3e8f..90b8d7b0 100644 +--- a/plugins/jj/jj.plugin.zsh ++++ b/plugins/jj/jj.plugin.zsh +@@ -45,34 +45,51 @@ alias jjbc='jj bookmark create' + alias jjbd='jj bookmark delete' + alias jjbf='jj bookmark forget' + alias jjbl='jj bookmark list' ++alias jjblt='jj bookmark list --tracked' + alias jjbm='jj bookmark move' + alias jjbr='jj bookmark rename' + alias jjbs='jj bookmark set' + alias jjbt='jj bookmark track' + alias jjbu='jj bookmark untrack' + alias jjc='jj commit' ++alias jjcfg='jj config' ++alias jjcfgl='jj config list' + alias jjcmsg='jj commit --message' + alias jjd='jj diff' + alias jjdmsg='jj desc --message' + alias jjds='jj desc' ++alias jjdst='jj diff --stat' + alias jje='jj edit' ++alias jjev='jj evolog' ++alias jjf='jj file' ++alias jjfl='jj file list' ++alias jjg='jj git' + alias jjgcl='jj git clone' + alias jjgf='jj git fetch' + alias jjgfa='jj git fetch --all-remotes' ++alias jjgi='jj git init' + alias jjgp='jj git push' + alias jjgpa='jj git push --all' + alias jjgpd='jj git push --deleted' + alias jjgpt='jj git push --tracked' ++alias jjgrl='jj git remote list' + alias jjl='jj log' + alias jjla='jj log -r "all()"' + alias jjn='jj new' + alias jjnt='jj new "trunk()"' ++alias jjop='jj op' ++alias jjopl='jj op log' ++alias jjor='jj op restore' + alias jjrb='jj rebase' + alias jjrbm='jj rebase -d "trunk()"' + alias jjrs='jj restore' + alias jjrt='cd "$(jj root || echo .)"' ++alias jjs='jj show' + alias jjsp='jj split' + alias jjsq='jj squash' + alias jjst='jj status' ++alias jju='jj undo' ++alias jjw='jj workspace' + alias jjwa='jj workspace add' + alias jjwf='jj workspace forget' ++alias jjwl='jj workspace list' diff --git a/tasks/ohmyzsh__ohmyzsh-13962/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-13962/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3cf2a0ac94b18cab9e0a9dae9c7f606a19bebe87 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13962/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 593e8ed6c8b4686654e1ff059d1e8e345082c848 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-13962/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-13962/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13962/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-13984/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-13984/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..53da579409fee42e2a92dcfa099cafb92bfad9a4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13984/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d42209f2afa8ec3e6971e5b4695ff27f9d5670d2 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d42209f2afa8ec3e6971e5b4695ff27f9d5670d2 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d42209f2afa8ec3e6971e5b4695ff27f9d5670d2 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-13984/instruction.md b/tasks/ohmyzsh__ohmyzsh-13984/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..13558fd4f5fec88c861d8e0cb46b0dd095dd6da3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13984/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** fix(mise): activate using `~/.local/bin/mise` + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [ ] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +Instead of expecting `mise` command to exist, follows the official guide to activate it: https://mise.jdx.dev/getting-started.html#activate-mise: + +> `echo 'eval "$(~/.local/bin/mise activate zsh)"' >> ~/.zshrc` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d42209f2afa8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13984/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-13984/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d1181459b15794db29e8d06a8c90d40648e9af3f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13984/solution/patch.diff @@ -0,0 +1,21 @@ +diff --git a/plugins/mise/mise.plugin.zsh b/plugins/mise/mise.plugin.zsh +index 96373f5d..b3dbcbc5 100644 +--- a/plugins/mise/mise.plugin.zsh ++++ b/plugins/mise/mise.plugin.zsh +@@ -1,9 +1,14 @@ +-if (( ! $+commands[mise] )); then ++if (( $+commands[mise] )); then ++ _mise_bin=mise ++elif [[ -x ~/.local/bin/mise ]]; then ++ _mise_bin=~/.local/bin/mise ++else + return + fi + + # Load mise hooks +-eval "$(mise activate zsh)" ++eval "$($_mise_bin activate zsh)" ++unset _mise_bin + + # If the completion file doesn't exist yet, we need to autoload it and + # bind it to `mise`. Otherwise, compinit will have already done that. diff --git a/tasks/ohmyzsh__ohmyzsh-13984/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-13984/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13984/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-13984/task.toml b/tasks/ohmyzsh__ohmyzsh-13984/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..948de731c8bbc95a81d33b2373392742499876a4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13984/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-13984" +description = "fix(mise): activate using `~/.local/bin/mise`" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "d42209f2afa8ec3e6971e5b4695ff27f9d5670d2" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/13984" +source_access = "auto" +built_at = "2026-11-16T16:09:57.011522+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:dd2d03a5a4ffd70785d347dc76d9d8f027a54930d241665ff6a5edd6a3fcff03" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-01T07:21:55Z" +diff_format = "unified" +context_files = [ + "plugins/mise/mise.plugin.zsh", +] +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.962860+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:7224af774609236635207841960d14c78f2be180a373bdeddd8fa5e56673a97d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-13984/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-13984/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13984/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-13984/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-13984/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..13558fd4f5fec88c861d8e0cb46b0dd095dd6da3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13984/tests/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** fix(mise): activate using `~/.local/bin/mise` + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [ ] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +Instead of expecting `mise` command to exist, follows the official guide to activate it: https://mise.jdx.dev/getting-started.html#activate-mise: + +> `echo 'eval "$(~/.local/bin/mise activate zsh)"' >> ~/.zshrc` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d42209f2afa8`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-13984/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-13984/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d1181459b15794db29e8d06a8c90d40648e9af3f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13984/tests/oracle.patch @@ -0,0 +1,21 @@ +diff --git a/plugins/mise/mise.plugin.zsh b/plugins/mise/mise.plugin.zsh +index 96373f5d..b3dbcbc5 100644 +--- a/plugins/mise/mise.plugin.zsh ++++ b/plugins/mise/mise.plugin.zsh +@@ -1,9 +1,14 @@ +-if (( ! $+commands[mise] )); then ++if (( $+commands[mise] )); then ++ _mise_bin=mise ++elif [[ -x ~/.local/bin/mise ]]; then ++ _mise_bin=~/.local/bin/mise ++else + return + fi + + # Load mise hooks +-eval "$(mise activate zsh)" ++eval "$($_mise_bin activate zsh)" ++unset _mise_bin + + # If the completion file doesn't exist yet, we need to autoload it and + # bind it to `mise`. Otherwise, compinit will have already done that. diff --git a/tasks/ohmyzsh__ohmyzsh-13984/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-13984/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d7d4d268e7785d8c821ca0b758e36c7739cedcc0 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13984/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d42209f2afa8ec3e6971e5b4695ff27f9d5670d2 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-13984/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-13984/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-13984/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14002/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14002/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..43ba59497d3118cbaa642e3f62637e12f4bd9497 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14002/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 830a5bcfd29fd577fdcd5f3b8e98cbaf973421fa 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 830a5bcfd29fd577fdcd5f3b8e98cbaf973421fa \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 830a5bcfd29fd577fdcd5f3b8e98cbaf973421fa \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14002/instruction.md b/tasks/ohmyzsh__ohmyzsh-14002/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a8720c2cfcde0e82e402e946766bc7ec2c567c1f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14002/instruction.md @@ -0,0 +1,69 @@ +# Issue + +**Title:** chore(deps): bump step-security/harden-runner from 2.20.1 to 2.21.0 in the gha-minor group + +## Description + +Bumps the gha-minor group with 1 update: [step-security/harden-runner](https://github.com/step-security/harden-runner). + +Updates `step-security/harden-runner` from 2.20.1 to 2.21.0 +
      +Release notes +

      Sourced from step-security/harden-runner's releases.

      +
      +

      v2.21.0

      +

      What's Changed

      +
        +
      • Support for denied endpoints in block mode. This is included in the enterprise tier. Customers can deny outbound calls, for example, to public package registries.
      • +
      • Improved Support for AWS CodeBuild GitHub Actions Runners.
      • +
      • Bug fixes.
      • +
      +

      Full Changelog: https://github.com/step-security/harden-runner/compare/v2.20.1...v2.21.0

      +
      +
      +
      +Commits +
        +
      • 05e3151 Merge pull request #684 from step-security/rc-42
      • +
      • 0f37afa fix: ignore denied-endpoints on non-enterprise tier
      • +
      • 93b58ee fix: resolve cache host read-first and never downgrade egress policy
      • +
      • e7399dd fix: align deny-list mode detection with agent and log when both endpoint inp...
      • +
      • c16689f test: add denied_endpoints to Configuration fixtures and cover deny-list merge
      • +
      • 40b99cf Merge pull request #682 from rohan-stepsecurity/rp/feat/codebuild-self-v2
      • +
      • fedec02 Merge branch 'rc-42' into rp/feat/codebuild-self-v2
      • +
      • 5361fb1 feat: add build artifacts
      • +
      • 286474f feat: Support Bravo agent install on CodeBuild runners
      • +
      • 051ec05 Merge pull request #683 from h0x0er/jatin/deny-list
      • +
      • Additional commits viewable in compare view
      • +
      +
      +
      + +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=step-security/harden-runner&package-manager=github_actions&previous-version=2.20.1&new-version=2.21.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) + +Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. + +[//]: # (dependabot-automerge-start) +[//]: # (dependabot-automerge-end) + +--- + +
      +Dependabot commands and options +
      + +You can trigger Dependabot actions by commenting on this PR: +- `@dependabot rebase` will rebase this PR +- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it +- `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency +- `@dependabot ignore major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) +- `@dependabot ignore minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) +- `@dependabot ignore ` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) +- `@dependabot unignore ` will remove all of the ignore conditions of the specified dependency +- `@dependabot unignore ` will remove the ignore condition of the specified dependency and ignore conditions + +
      + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `830a5bcfd29f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14002/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14002/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..97784b997f6706c48bc02c00ab6487b44b7defaa --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14002/solution/patch.diff @@ -0,0 +1,74 @@ +diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml +index 212cfbf0..2389544f 100644 +--- a/.github/workflows/dependencies.yml ++++ b/.github/workflows/dependencies.yml +@@ -16,7 +16,7 @@ jobs: + contents: write # this is needed to push commits and branches + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 ++ uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 + with: + egress-policy: audit + +diff --git a/.github/workflows/installer.yml b/.github/workflows/installer.yml +index 04acc67a..cb5acc54 100644 +--- a/.github/workflows/installer.yml ++++ b/.github/workflows/installer.yml +@@ -26,7 +26,7 @@ jobs: + - macos-latest + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 ++ uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 + with: + egress-policy: audit + +@@ -47,7 +47,7 @@ jobs: + - test + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 ++ uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 + with: + egress-policy: audit + +diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml +index 8b83613d..6354caae 100644 +--- a/.github/workflows/main.yml ++++ b/.github/workflows/main.yml +@@ -24,7 +24,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 ++ uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 + with: + egress-policy: audit + +diff --git a/.github/workflows/project.yml b/.github/workflows/project.yml +index f6daabdb..d3a2cd8f 100644 +--- a/.github/workflows/project.yml ++++ b/.github/workflows/project.yml +@@ -17,7 +17,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 ++ uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 + with: + egress-policy: audit + - name: Authenticate as @ohmyzsh +diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml +index 46c9d956..0f3684d1 100644 +--- a/.github/workflows/scorecard.yml ++++ b/.github/workflows/scorecard.yml +@@ -36,7 +36,7 @@ jobs: + + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 ++ uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 + with: + egress-policy: audit + diff --git a/tasks/ohmyzsh__ohmyzsh-14002/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14002/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14002/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14002/task.toml b/tasks/ohmyzsh__ohmyzsh-14002/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1a464cd66db82c9519cd2894a76b660f58574416 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14002/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14002" +description = "chore(deps): bump step-security/harden-runner from 2.20.1 to 2.21.0 in the gha-minor group" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "830a5bcfd29fd577fdcd5f3b8e98cbaf973421fa" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14002" +source_access = "auto" +built_at = "2026-11-16T16:09:57.022355+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7eec5f692c8dd1916d95681e288daf64f666521cb4f895c658a28a1f909bc678" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-24T06:41:52Z" +diff_format = "unified" +context_files = [ + ".github/workflows/dependencies.yml", + ".github/workflows/installer.yml", + ".github/workflows/main.yml", + ".github/workflows/project.yml", + ".github/workflows/scorecard.yml", +] +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.963543+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1570baa20267829d013a63ee7133a7bb96e1c96dc27a941b35101d0149262674" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14002/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14002/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14002/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14002/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14002/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a8720c2cfcde0e82e402e946766bc7ec2c567c1f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14002/tests/instruction.md @@ -0,0 +1,69 @@ +# Issue + +**Title:** chore(deps): bump step-security/harden-runner from 2.20.1 to 2.21.0 in the gha-minor group + +## Description + +Bumps the gha-minor group with 1 update: [step-security/harden-runner](https://github.com/step-security/harden-runner). + +Updates `step-security/harden-runner` from 2.20.1 to 2.21.0 +
      +Release notes +

      Sourced from step-security/harden-runner's releases.

      +
      +

      v2.21.0

      +

      What's Changed

      +
        +
      • Support for denied endpoints in block mode. This is included in the enterprise tier. Customers can deny outbound calls, for example, to public package registries.
      • +
      • Improved Support for AWS CodeBuild GitHub Actions Runners.
      • +
      • Bug fixes.
      • +
      +

      Full Changelog: https://github.com/step-security/harden-runner/compare/v2.20.1...v2.21.0

      +
      +
      +
      +Commits +
        +
      • 05e3151 Merge pull request #684 from step-security/rc-42
      • +
      • 0f37afa fix: ignore denied-endpoints on non-enterprise tier
      • +
      • 93b58ee fix: resolve cache host read-first and never downgrade egress policy
      • +
      • e7399dd fix: align deny-list mode detection with agent and log when both endpoint inp...
      • +
      • c16689f test: add denied_endpoints to Configuration fixtures and cover deny-list merge
      • +
      • 40b99cf Merge pull request #682 from rohan-stepsecurity/rp/feat/codebuild-self-v2
      • +
      • fedec02 Merge branch 'rc-42' into rp/feat/codebuild-self-v2
      • +
      • 5361fb1 feat: add build artifacts
      • +
      • 286474f feat: Support Bravo agent install on CodeBuild runners
      • +
      • 051ec05 Merge pull request #683 from h0x0er/jatin/deny-list
      • +
      • Additional commits viewable in compare view
      • +
      +
      +
      + +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=step-security/harden-runner&package-manager=github_actions&previous-version=2.20.1&new-version=2.21.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) + +Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. + +[//]: # (dependabot-automerge-start) +[//]: # (dependabot-automerge-end) + +--- + +
      +Dependabot commands and options +
      + +You can trigger Dependabot actions by commenting on this PR: +- `@dependabot rebase` will rebase this PR +- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it +- `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency +- `@dependabot ignore major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) +- `@dependabot ignore minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) +- `@dependabot ignore ` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) +- `@dependabot unignore ` will remove all of the ignore conditions of the specified dependency +- `@dependabot unignore ` will remove the ignore condition of the specified dependency and ignore conditions + +
      + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `830a5bcfd29f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14002/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14002/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..97784b997f6706c48bc02c00ab6487b44b7defaa --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14002/tests/oracle.patch @@ -0,0 +1,74 @@ +diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml +index 212cfbf0..2389544f 100644 +--- a/.github/workflows/dependencies.yml ++++ b/.github/workflows/dependencies.yml +@@ -16,7 +16,7 @@ jobs: + contents: write # this is needed to push commits and branches + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 ++ uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 + with: + egress-policy: audit + +diff --git a/.github/workflows/installer.yml b/.github/workflows/installer.yml +index 04acc67a..cb5acc54 100644 +--- a/.github/workflows/installer.yml ++++ b/.github/workflows/installer.yml +@@ -26,7 +26,7 @@ jobs: + - macos-latest + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 ++ uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 + with: + egress-policy: audit + +@@ -47,7 +47,7 @@ jobs: + - test + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 ++ uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 + with: + egress-policy: audit + +diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml +index 8b83613d..6354caae 100644 +--- a/.github/workflows/main.yml ++++ b/.github/workflows/main.yml +@@ -24,7 +24,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 ++ uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 + with: + egress-policy: audit + +diff --git a/.github/workflows/project.yml b/.github/workflows/project.yml +index f6daabdb..d3a2cd8f 100644 +--- a/.github/workflows/project.yml ++++ b/.github/workflows/project.yml +@@ -17,7 +17,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 ++ uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 + with: + egress-policy: audit + - name: Authenticate as @ohmyzsh +diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml +index 46c9d956..0f3684d1 100644 +--- a/.github/workflows/scorecard.yml ++++ b/.github/workflows/scorecard.yml +@@ -36,7 +36,7 @@ jobs: + + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@b09bb98e06d4d774595224525879c09bc6e98c40 # v2.20.1 ++ uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 + with: + egress-policy: audit + diff --git a/tasks/ohmyzsh__ohmyzsh-14002/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14002/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9f9c37ae53f523587ffd0bda4825a043512e857e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14002/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 830a5bcfd29fd577fdcd5f3b8e98cbaf973421fa > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14002/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14002/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14002/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14004/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14004/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..29750c91d8c64565d89306384065f13f63e96055 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14004/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 67462daf46ebda490dbc5e1629c0ee4f72536bb6 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 67462daf46ebda490dbc5e1629c0ee4f72536bb6 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 67462daf46ebda490dbc5e1629c0ee4f72536bb6 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14004/instruction.md b/tasks/ohmyzsh__ohmyzsh-14004/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7fc3b55b65420954b380533212b54108a302a57c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14004/instruction.md @@ -0,0 +1,67 @@ +# Issue + +**Title:** fix(docker): resolve completion path correctly in anonymous function + +## Description + +## Description + +Fix the legacy Docker completion path resolution inside the background +anonymous function. + +Inside the anonymous function, `$0` refers to the function itself rather +than `plugins/docker/docker.plugin.zsh`. As a result, using `$0` from +inside the function can resolve the bundled completion file from an +incorrect directory. + +This change evaluates `${0:A:h}` before entering the anonymous function, +passes the absolute plugin directory as an argument, and stores it in the +local `plugin_dir` variable. + +The legacy completion file is then resolved using: + +```zsh +"${plugin_dir}/completions/_docker" +``` + + + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [ ] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- [fix/docker-completion-cache](https://github.com/sony-level/ohmyzsh/compare/fix/docker-completion-cache) + +## Other comments: + +Tested with: + +- Debian GNU/Linux 13 (trixie) +- Zsh 5.9 +- Docker 26.1.5+dfsg1 +- Docker legacy completion enabled + +Checks performed: + +- Run `zsh -n plugins/docker/docker.plugin.zsh.` +- Started a new Zsh session with legacy Docker completion enabled. +- Verified that the completion cache was generated without the incorrect path error. +- Verified completion for Docker commands. + +... + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `67462daf46eb`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14004/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14004/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..02f5930fa85258ed3f9008e10205712616df4457 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14004/solution/patch.diff @@ -0,0 +1,24 @@ +diff --git a/plugins/docker/docker.plugin.zsh b/plugins/docker/docker.plugin.zsh +index d07ae603..5d1a67e7 100644 +--- a/plugins/docker/docker.plugin.zsh ++++ b/plugins/docker/docker.plugin.zsh +@@ -58,14 +58,17 @@ fi + + zmodload -F zsh/files b:zf_mv + () { ++ ++ local plugin_dir="$1" ++ + # `docker completion` is only available from 23.0.0 on + # docker version returns `Docker version 24.0.2, build cb74dfcd85` + # with `s:,:` remove the comma after the version, and select third word of it + if zstyle -t ':omz:plugins:docker' legacy-completion || \ + ! is-at-least 23.0.0 ${${(s:,:z)"$(command docker --version)"}[3]}; then +- command cp "${0:h}/completions/_docker" "$ZSH_CACHE_DIR/completions/_docker" ++ command cp "${plugin_dir}/completions/_docker" "$ZSH_CACHE_DIR/completions/_docker" + else + local TMPPREFIX="$ZSH_CACHE_DIR/completions/_docker" + zf_mv -f -- =( command docker completion zsh ) "$TMPPREFIX" + fi +-} &| ++} "${0:A:h}" &| diff --git a/tasks/ohmyzsh__ohmyzsh-14004/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14004/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14004/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14004/task.toml b/tasks/ohmyzsh__ohmyzsh-14004/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6bb6991358d63e404b3a79eaf6177d09d5120a7c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14004/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14004" +description = "fix(docker): resolve completion path correctly in anonymous function" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "67462daf46ebda490dbc5e1629c0ee4f72536bb6" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14004" +source_access = "auto" +built_at = "2026-11-16T16:09:57.020252+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b2db7a4e70fa53659f6179843166496f4a80c39aab5d71fce79ff5fadf736ecc" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-24T16:33:49Z" +diff_format = "unified" +context_files = [ + "plugins/docker/docker.plugin.zsh", +] +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.964523+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a166f952a71ec88656320776919db4999c0a868940626f3f10a0cd71c1d1a67c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14004/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14004/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14004/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14004/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14004/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7fc3b55b65420954b380533212b54108a302a57c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14004/tests/instruction.md @@ -0,0 +1,67 @@ +# Issue + +**Title:** fix(docker): resolve completion path correctly in anonymous function + +## Description + +## Description + +Fix the legacy Docker completion path resolution inside the background +anonymous function. + +Inside the anonymous function, `$0` refers to the function itself rather +than `plugins/docker/docker.plugin.zsh`. As a result, using `$0` from +inside the function can resolve the bundled completion file from an +incorrect directory. + +This change evaluates `${0:A:h}` before entering the anonymous function, +passes the absolute plugin directory as an argument, and stores it in the +local `plugin_dir` variable. + +The legacy completion file is then resolved using: + +```zsh +"${plugin_dir}/completions/_docker" +``` + + + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [ ] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- [fix/docker-completion-cache](https://github.com/sony-level/ohmyzsh/compare/fix/docker-completion-cache) + +## Other comments: + +Tested with: + +- Debian GNU/Linux 13 (trixie) +- Zsh 5.9 +- Docker 26.1.5+dfsg1 +- Docker legacy completion enabled + +Checks performed: + +- Run `zsh -n plugins/docker/docker.plugin.zsh.` +- Started a new Zsh session with legacy Docker completion enabled. +- Verified that the completion cache was generated without the incorrect path error. +- Verified completion for Docker commands. + +... + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `67462daf46eb`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14004/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14004/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..02f5930fa85258ed3f9008e10205712616df4457 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14004/tests/oracle.patch @@ -0,0 +1,24 @@ +diff --git a/plugins/docker/docker.plugin.zsh b/plugins/docker/docker.plugin.zsh +index d07ae603..5d1a67e7 100644 +--- a/plugins/docker/docker.plugin.zsh ++++ b/plugins/docker/docker.plugin.zsh +@@ -58,14 +58,17 @@ fi + + zmodload -F zsh/files b:zf_mv + () { ++ ++ local plugin_dir="$1" ++ + # `docker completion` is only available from 23.0.0 on + # docker version returns `Docker version 24.0.2, build cb74dfcd85` + # with `s:,:` remove the comma after the version, and select third word of it + if zstyle -t ':omz:plugins:docker' legacy-completion || \ + ! is-at-least 23.0.0 ${${(s:,:z)"$(command docker --version)"}[3]}; then +- command cp "${0:h}/completions/_docker" "$ZSH_CACHE_DIR/completions/_docker" ++ command cp "${plugin_dir}/completions/_docker" "$ZSH_CACHE_DIR/completions/_docker" + else + local TMPPREFIX="$ZSH_CACHE_DIR/completions/_docker" + zf_mv -f -- =( command docker completion zsh ) "$TMPPREFIX" + fi +-} &| ++} "${0:A:h}" &| diff --git a/tasks/ohmyzsh__ohmyzsh-14004/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14004/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0fcc4e728ca97385c8b5cc09c3c20acc902f1ae5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14004/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 67462daf46ebda490dbc5e1629c0ee4f72536bb6 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14004/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14004/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14004/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14006/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14006/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bf197fc17a7e0035af23fde8dac2f1e3dfdbcd1c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14006/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin ec03bc620c8a9e30f74e6fcc6dc171a35cd82b1f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard ec03bc620c8a9e30f74e6fcc6dc171a35cd82b1f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base ec03bc620c8a9e30f74e6fcc6dc171a35cd82b1f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14006/instruction.md b/tasks/ohmyzsh__ohmyzsh-14006/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7e2f738199bce0c8565870f5ffa2700efd8b0290 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14006/instruction.md @@ -0,0 +1,39 @@ +# Issue + +**Title:** fix(git): force C locale only while matching status regexes + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. + +## Changes: + +, without undoing what #13878 was trying to do. + +The short version: `898b579` set `LC_ALL=C` for the whole `_omz_git_prompt_status` function to stop the regex from choking on invalid byte sequences (#13330). That works, but it's broader than intended — zsh re-runs `setlocale()` as soon as `LC_ALL` is assigned, so the rest of the function also runs under the C locale. When a theme uses a Unicode escape like `\U2731` for its prompt glyphs, the final `echo` can't map it to a character anymore and dies with `character not in range`, which is exactly the error reported in #13985. + +So this moves the locale forcing into a tiny helper (`_omz_git_prompt_status_match`) that wraps each individual `[[ =~ ]]` check. The three call sites that parse porcelain output still get the C locale (that part of #13878 stays intact), while everything else — most importantly printing the theme symbols — keeps the user's own locale. `$match` etc. are global special parameters, so nothing changes about how matches are consumed afterwards. + +For testing I ran this on an Ubuntu 24.04 container with zsh 5.9: + +- the reporter's exact scenario now renders the glyph instead of erroring +- a repo with a non-UTF-8 filename no longer triggers "illegal byte sequence" (#13330 case) +- ahead / behind / diverged tracking-line parsing gives identical output to unmodified master +- full `oh-my-zsh.sh` startup smoke test passes; `zsh -n` is clean + +## Other comments: + +AI disclosure: this patch was prepared with the help of an AI coding agent (root-cause analysis and draft). I reproduced the bug locally, reviewed the change line by line, and ran the tests listed above myself before submitting. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ec03bc620c8a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14006/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14006/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4b11b2b9ac0ce6ac478e794f638c948af283fd88 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14006/solution/patch.diff @@ -0,0 +1,63 @@ +diff --git a/lib/git.zsh b/lib/git.zsh +index 6d7c2c7d..41d01f66 100644 +--- a/lib/git.zsh ++++ b/lib/git.zsh +@@ -39,16 +39,27 @@ function _omz_git_prompt_info() { + echo "${ZSH_THEME_GIT_PROMPT_PREFIX}${ref//\%/%%}${upstream//\%/%%}$(parse_git_dirty)${ZSH_THEME_GIT_PROMPT_SUFFIX}" + } + +-function _omz_git_prompt_status() { +- # OHMYZSH-13330: avoid "regex matching error: illegal byte sequence". +- # zsh's "=~" operator delegates to the C library regex, which aborts with +- # REG_ILLSEQ when the subject contains an invalid byte sequence under a +- # multibyte locale (e.g. a filename with non-UTF-8 bytes in `git status` +- # output). Forcing the C locale makes every byte a valid character, so the +- # regex matching below never fails that way. `git status --porcelain` is +- # locale-independent, so this does not change the parsed output. ++# Match an extended regular expression against a subject, forcing the C locale ++# only for the duration of the call. ++# ++# OHMYZSH-13330: zsh's "=~" operator delegates to the C library regex, which ++# aborts with REG_ILLSEQ when the subject contains an invalid byte sequence ++# under a multibyte locale (e.g. a filename with non-UTF-8 bytes in `git ++# status` output). Forcing the C locale makes every byte a valid character, ++# so the regex matching never fails that way. `git status --porcelain` is ++# locale-independent, so this does not change the parsed output. ++# ++# OHMYZSH-13985: the locale must be scoped to this function and not set for ++# the whole caller. Assigning LC_ALL makes zsh re-run setlocale() right away, ++# so leaving it set while the rest of the caller runs breaks multibyte ++# handling there — most visibly, `echo` refuses to expand Unicode escapes in ++# theme prompt symbols ("character not in range"). ++function _omz_git_prompt_status_match() { + local -x LC_ALL=C ++ [[ "$1" =~ "$2" ]] ++} + ++function _omz_git_prompt_status() { + [[ "$(__git_prompt_git config --get oh-my-zsh.hide-status 2>/dev/null)" = 1 ]] && return + + # Maps a git status prefix to an internal constant +@@ -113,11 +124,11 @@ function _omz_git_prompt_status() { + status_lines=("${(@f)${status_text}}") + + # If the tracking line exists, get and parse it +- if [[ "$status_lines[1]" =~ "^## [^ ]+ \[(.*)\]" ]]; then ++ if _omz_git_prompt_status_match "$status_lines[1]" "^## [^ ]+ \[(.*)\]"; then + local branch_statuses + branch_statuses=("${(@s/,/)match}") + for branch_status in $branch_statuses; do +- if [[ ! $branch_status =~ "(behind|diverged|ahead) ([0-9]+)?" ]]; then ++ if ! _omz_git_prompt_status_match "$branch_status" "(behind|diverged|ahead) ([0-9]+)?"; then + continue + fi + local last_parsed_status=$prefix_constant_map[$match[1]] +@@ -130,7 +141,7 @@ function _omz_git_prompt_status() { + local status_constant="${prefix_constant_map[$status_prefix]}" + local status_regex=$'(^|\n)'"$status_prefix" + +- if [[ "$status_text" =~ $status_regex ]]; then ++ if _omz_git_prompt_status_match "$status_text" "$status_regex"; then + statuses_seen[$status_constant]=1 + fi + done diff --git a/tasks/ohmyzsh__ohmyzsh-14006/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14006/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14006/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14006/task.toml b/tasks/ohmyzsh__ohmyzsh-14006/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f0405269727cff8d92b9c86a09ed422501e4431c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14006/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14006" +description = "fix(git): force C locale only while matching status regexes" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "ec03bc620c8a9e30f74e6fcc6dc171a35cd82b1f" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14006" +source_access = "auto" +built_at = "2026-11-16T16:09:57.018383+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:de2d24a51d3477c257571d09dc4b59c73da2741db26e1142bef179fdd7c255e0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-25T08:26:24Z" +diff_format = "unified" +context_files = [ + "lib/git.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 33 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.965063+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b7135df40a36c957b8903fc2f82bc98db2d2d9cfb04cf4172cb6d8fa51a48eb6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14006/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14006/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14006/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14006/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14006/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7e2f738199bce0c8565870f5ffa2700efd8b0290 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14006/tests/instruction.md @@ -0,0 +1,39 @@ +# Issue + +**Title:** fix(git): force C locale only while matching status regexes + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. + +## Changes: + +, without undoing what #13878 was trying to do. + +The short version: `898b579` set `LC_ALL=C` for the whole `_omz_git_prompt_status` function to stop the regex from choking on invalid byte sequences (#13330). That works, but it's broader than intended — zsh re-runs `setlocale()` as soon as `LC_ALL` is assigned, so the rest of the function also runs under the C locale. When a theme uses a Unicode escape like `\U2731` for its prompt glyphs, the final `echo` can't map it to a character anymore and dies with `character not in range`, which is exactly the error reported in #13985. + +So this moves the locale forcing into a tiny helper (`_omz_git_prompt_status_match`) that wraps each individual `[[ =~ ]]` check. The three call sites that parse porcelain output still get the C locale (that part of #13878 stays intact), while everything else — most importantly printing the theme symbols — keeps the user's own locale. `$match` etc. are global special parameters, so nothing changes about how matches are consumed afterwards. + +For testing I ran this on an Ubuntu 24.04 container with zsh 5.9: + +- the reporter's exact scenario now renders the glyph instead of erroring +- a repo with a non-UTF-8 filename no longer triggers "illegal byte sequence" (#13330 case) +- ahead / behind / diverged tracking-line parsing gives identical output to unmodified master +- full `oh-my-zsh.sh` startup smoke test passes; `zsh -n` is clean + +## Other comments: + +AI disclosure: this patch was prepared with the help of an AI coding agent (root-cause analysis and draft). I reproduced the bug locally, reviewed the change line by line, and ran the tests listed above myself before submitting. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `ec03bc620c8a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14006/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14006/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4b11b2b9ac0ce6ac478e794f638c948af283fd88 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14006/tests/oracle.patch @@ -0,0 +1,63 @@ +diff --git a/lib/git.zsh b/lib/git.zsh +index 6d7c2c7d..41d01f66 100644 +--- a/lib/git.zsh ++++ b/lib/git.zsh +@@ -39,16 +39,27 @@ function _omz_git_prompt_info() { + echo "${ZSH_THEME_GIT_PROMPT_PREFIX}${ref//\%/%%}${upstream//\%/%%}$(parse_git_dirty)${ZSH_THEME_GIT_PROMPT_SUFFIX}" + } + +-function _omz_git_prompt_status() { +- # OHMYZSH-13330: avoid "regex matching error: illegal byte sequence". +- # zsh's "=~" operator delegates to the C library regex, which aborts with +- # REG_ILLSEQ when the subject contains an invalid byte sequence under a +- # multibyte locale (e.g. a filename with non-UTF-8 bytes in `git status` +- # output). Forcing the C locale makes every byte a valid character, so the +- # regex matching below never fails that way. `git status --porcelain` is +- # locale-independent, so this does not change the parsed output. ++# Match an extended regular expression against a subject, forcing the C locale ++# only for the duration of the call. ++# ++# OHMYZSH-13330: zsh's "=~" operator delegates to the C library regex, which ++# aborts with REG_ILLSEQ when the subject contains an invalid byte sequence ++# under a multibyte locale (e.g. a filename with non-UTF-8 bytes in `git ++# status` output). Forcing the C locale makes every byte a valid character, ++# so the regex matching never fails that way. `git status --porcelain` is ++# locale-independent, so this does not change the parsed output. ++# ++# OHMYZSH-13985: the locale must be scoped to this function and not set for ++# the whole caller. Assigning LC_ALL makes zsh re-run setlocale() right away, ++# so leaving it set while the rest of the caller runs breaks multibyte ++# handling there — most visibly, `echo` refuses to expand Unicode escapes in ++# theme prompt symbols ("character not in range"). ++function _omz_git_prompt_status_match() { + local -x LC_ALL=C ++ [[ "$1" =~ "$2" ]] ++} + ++function _omz_git_prompt_status() { + [[ "$(__git_prompt_git config --get oh-my-zsh.hide-status 2>/dev/null)" = 1 ]] && return + + # Maps a git status prefix to an internal constant +@@ -113,11 +124,11 @@ function _omz_git_prompt_status() { + status_lines=("${(@f)${status_text}}") + + # If the tracking line exists, get and parse it +- if [[ "$status_lines[1]" =~ "^## [^ ]+ \[(.*)\]" ]]; then ++ if _omz_git_prompt_status_match "$status_lines[1]" "^## [^ ]+ \[(.*)\]"; then + local branch_statuses + branch_statuses=("${(@s/,/)match}") + for branch_status in $branch_statuses; do +- if [[ ! $branch_status =~ "(behind|diverged|ahead) ([0-9]+)?" ]]; then ++ if ! _omz_git_prompt_status_match "$branch_status" "(behind|diverged|ahead) ([0-9]+)?"; then + continue + fi + local last_parsed_status=$prefix_constant_map[$match[1]] +@@ -130,7 +141,7 @@ function _omz_git_prompt_status() { + local status_constant="${prefix_constant_map[$status_prefix]}" + local status_regex=$'(^|\n)'"$status_prefix" + +- if [[ "$status_text" =~ $status_regex ]]; then ++ if _omz_git_prompt_status_match "$status_text" "$status_regex"; then + statuses_seen[$status_constant]=1 + fi + done diff --git a/tasks/ohmyzsh__ohmyzsh-14006/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14006/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..69ec7bfc3a1dc8cb474cf7ebe15123ae555b428f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14006/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace ec03bc620c8a9e30f74e6fcc6dc171a35cd82b1f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14006/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14006/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14006/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14021/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14021/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..59c1a16c2256f15de0df7a1312621bd147b28d0c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14021/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 146461f7c6d95f4ba1220559d66eb113418b40a8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 146461f7c6d95f4ba1220559d66eb113418b40a8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 146461f7c6d95f4ba1220559d66eb113418b40a8 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14021/instruction.md b/tasks/ohmyzsh__ohmyzsh-14021/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..84ebbe7a5fb0626799f1071ea27fd7c8b3713c0e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14021/instruction.md @@ -0,0 +1,74 @@ +# Issue + +**Title:** fix(pipenv): keep activation and the project directory in sync + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. + +## Changes: + +, and fixes a second bug in the same hook that I found while testing it. + +`_togglePipenvShell` gets its two halves wrong in ways that both leave the shell claiming a state it does not have. Two commits, one per bug. + +**Commit 1 — activation is unguarded (#10600).** When a `Pipfile` exists but its virtualenv does not, `source "$(pipenv --venv)/bin/activate"` runs with no error handling, so: + +- `pipenv --venv`'s complaint (in some versions a full Python traceback) goes straight to the shell's startup output; +- `$(pipenv --venv)` expands to empty and zsh tries to `source /bin/activate`, printing `no such file or directory`; +- `PIPENV_ACTIVE=1` and `pipfile_dir` are exported anyway although nothing was activated, which blocks every later activation attempt in that shell; +- and because `PIPENV_ACTIVE=1` was set anyway, the *next* `cd` out of the directory takes the deactivation branch and calls a `deactivate` function that no activate script ever defined. + +Activation now happens only when `pipenv --venv` succeeds **and** the activate script exists. This also removes the follow-on `command not found: deactivate`, since that state is never entered. + +**Commit 2 — the directory test uses string prefixes, not path components.** The deactivation guard is `[[ "$PWD" != "$pipfile_dir"* ]]`, which is true for subdirectories of the project (intended) but also for unrelated siblings that merely start with the same characters: `…/proj` → `…/proj-archive` or `…/projX` keeps the virtualenv active in a directory that has no `Pipfile` at all, and `PIPENV_ACTIVE` stays `1`. Fixed by requiring either an exact match or a `/` component boundary. Subdirectory behaviour is unchanged, and a project at `/` still matches everything. + +Same class of slip as the one fixed for the git prompt in #14006. `poetry-env` has the identical prefix test on line 9 of its plugin (`"$PWD" != "$poetry_dir"*`), so it has the same bug — I left that file alone because #13932 is already open against it, but noted it there. + +## Testing: + +Stubbed `pipenv` driving each toolchain state, capturing stderr per step, run against this branch and `origin/master`; every cell reproduced on three consecutive runs. zsh 5.9 (the CI job is a single `ubuntu-latest` + apt zsh with no version matrix, so I am not claiming coverage beyond that one version). + +| case | master | this branch | +|---|---|---| +| `Pipfile` present, venv missing (startup) | `pipenv` stderr leaks + `source:…: no such file or directory: /bin/activate` + `PIPENV_ACTIVE=1` while `VIRTUAL_ENV` unset | silent; `PIPENV_ACTIVE`/`pipfile_dir` stay unset | +| …then `cd` out of that directory | `command not found: deactivate` | silent | +| `--venv` prints a path with no `bin/activate` | same failure class | silent, stays inactive | +| healthy venv, start in project | `PIPENV_ACTIVE=1`, `VIRTUAL_ENV` set, `deactivate` defined | identical | +| healthy: project → elsewhere → back | activates → inactive → re-activates, stderr empty | identical | +| **project → unrelated `proj-archive` sibling** | ⚠️ stays active: `VIRTUAL_ENV= PIPENV_ACTIVE=1` | ✅ `VIRTUAL_ENV= PIPENV_ACTIVE=` | +| **project → `…/proj-archive/empty`** | ⚠️ still active | ✅ still inactive | +| **deep subdir *inside* the project** (no `Pipfile` there) | stays active | stays active (unchanged) | + +The boundary logic as a truth table (`stay` = keep virtualenv): + +| `pipfile_dir` | `PWD` | master | this branch | +|---|---|---|---| +| `/x/proj` | `/x/proj` | stay | stay | +| `/x/proj` | `/x/proj/src` | stay | stay | +| `/x/proj` | `/x/proj-archive` | ⚠️ stay | ✅ deactivate | +| `/x/proj` | `/x/projX` | ⚠️ stay | ✅ deactivate | +| `/` | `/tmp` | stay | stay | + +`zsh -n` passes on the plugin and the CI syntax sweep (`oh-my-zsh.sh`, `lib/*.zsh`, `plugins/*/*.plugin.zsh`, `plugins/*/_*`, `themes/*.zsh-theme`) is clean on this branch. + +## Other comments: + +If you would rather have these as two PRs, say the word and I will split commit 2 out onto its own branch — they are independent and each reverts cleanly on its own. They share a file and a function, which is why they are together here. + +The two new `[[ … ]]` operands and the `local project_dir` add no measurable startup cost: the guard is a shell builtin pattern match on variables that are already set, and the previously measured `pipenv --venv` call still happens exactly once per activation attempt as before. + +AI disclosure: this patch was prepared with the help of an AI coding agent (root-cause analysis, patch draft, and test harness). I reviewed every changed line and re-ran the tables above against both branches myself before submitting. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `146461f7c6d9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14021/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14021/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5f460c46997da178b3f73a8bb0b10a4c54856f11 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14021/solution/patch.diff @@ -0,0 +1,36 @@ +diff --git a/plugins/pipenv/pipenv.plugin.zsh b/plugins/pipenv/pipenv.plugin.zsh +index 82ad2b75..8b943041 100644 +--- a/plugins/pipenv/pipenv.plugin.zsh ++++ b/plugins/pipenv/pipenv.plugin.zsh +@@ -56,19 +56,26 @@ if zstyle -T ':omz:plugins:pipenv' auto-shell; then + # deactivate shell if Pipfile doesn't exist and not in a subdir + if [[ ! -f "$PWD/Pipfile" ]]; then + if [[ "$PIPENV_ACTIVE" == 1 ]]; then +- if [[ "$PWD" != "$pipfile_dir"* ]]; then ++ # Compare whole path components: `$pipfile_dir"*` also matches unrelated ++ # siblings that merely start with the same text (…/proj -> …/proj-docs), ++ # which would keep the virtualenv active outside the project. ++ local project_dir="${pipfile_dir%/}" ++ if [[ "$PWD" != "$project_dir" && "$PWD" != "$project_dir"/* ]]; then + unset PIPENV_ACTIVE pipfile_dir + deactivate + fi + fi + fi + +- # activate the shell if Pipfile exists ++ # activate the shell if Pipfile exists and its virtualenv is usable + if [[ "$PIPENV_ACTIVE" != 1 ]]; then + if [[ -f "$PWD/Pipfile" ]]; then +- export pipfile_dir="$PWD" +- source "$(pipenv --venv)/bin/activate" +- export PIPENV_ACTIVE=1 ++ local venv_path ++ if venv_path="$(pipenv --venv 2>/dev/null)" && [[ -n "$venv_path" && -f "$venv_path/bin/activate" ]]; then ++ export pipfile_dir="$PWD" ++ source "$venv_path/bin/activate" ++ export PIPENV_ACTIVE=1 ++ fi + fi + fi + } diff --git a/tasks/ohmyzsh__ohmyzsh-14021/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14021/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14021/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14021/task.toml b/tasks/ohmyzsh__ohmyzsh-14021/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..85b8e3247d4e8ef506db224207067465ca98fc1c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14021/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14021" +description = "fix(pipenv): keep activation and the project directory in sync" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "146461f7c6d95f4ba1220559d66eb113418b40a8" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14021" +source_access = "auto" +built_at = "2026-11-16T16:09:57.003467+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:95aade19fea3c336bb8c98cbd610273746d13d44b203e7af5703ceaad2d920a4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-05T19:13:52Z" +diff_format = "unified" +context_files = [ + "plugins/pipenv/pipenv.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 17 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.965735+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ff7f138bd9df2f2c0c5639aaf8e83a1463a9fbbeaf554c71f007edbd79847218" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14021/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14021/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14021/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14021/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14021/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..84ebbe7a5fb0626799f1071ea27fd7c8b3713c0e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14021/tests/instruction.md @@ -0,0 +1,74 @@ +# Issue + +**Title:** fix(pipenv): keep activation and the project directory in sync + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. + +## Changes: + +, and fixes a second bug in the same hook that I found while testing it. + +`_togglePipenvShell` gets its two halves wrong in ways that both leave the shell claiming a state it does not have. Two commits, one per bug. + +**Commit 1 — activation is unguarded (#10600).** When a `Pipfile` exists but its virtualenv does not, `source "$(pipenv --venv)/bin/activate"` runs with no error handling, so: + +- `pipenv --venv`'s complaint (in some versions a full Python traceback) goes straight to the shell's startup output; +- `$(pipenv --venv)` expands to empty and zsh tries to `source /bin/activate`, printing `no such file or directory`; +- `PIPENV_ACTIVE=1` and `pipfile_dir` are exported anyway although nothing was activated, which blocks every later activation attempt in that shell; +- and because `PIPENV_ACTIVE=1` was set anyway, the *next* `cd` out of the directory takes the deactivation branch and calls a `deactivate` function that no activate script ever defined. + +Activation now happens only when `pipenv --venv` succeeds **and** the activate script exists. This also removes the follow-on `command not found: deactivate`, since that state is never entered. + +**Commit 2 — the directory test uses string prefixes, not path components.** The deactivation guard is `[[ "$PWD" != "$pipfile_dir"* ]]`, which is true for subdirectories of the project (intended) but also for unrelated siblings that merely start with the same characters: `…/proj` → `…/proj-archive` or `…/projX` keeps the virtualenv active in a directory that has no `Pipfile` at all, and `PIPENV_ACTIVE` stays `1`. Fixed by requiring either an exact match or a `/` component boundary. Subdirectory behaviour is unchanged, and a project at `/` still matches everything. + +Same class of slip as the one fixed for the git prompt in #14006. `poetry-env` has the identical prefix test on line 9 of its plugin (`"$PWD" != "$poetry_dir"*`), so it has the same bug — I left that file alone because #13932 is already open against it, but noted it there. + +## Testing: + +Stubbed `pipenv` driving each toolchain state, capturing stderr per step, run against this branch and `origin/master`; every cell reproduced on three consecutive runs. zsh 5.9 (the CI job is a single `ubuntu-latest` + apt zsh with no version matrix, so I am not claiming coverage beyond that one version). + +| case | master | this branch | +|---|---|---| +| `Pipfile` present, venv missing (startup) | `pipenv` stderr leaks + `source:…: no such file or directory: /bin/activate` + `PIPENV_ACTIVE=1` while `VIRTUAL_ENV` unset | silent; `PIPENV_ACTIVE`/`pipfile_dir` stay unset | +| …then `cd` out of that directory | `command not found: deactivate` | silent | +| `--venv` prints a path with no `bin/activate` | same failure class | silent, stays inactive | +| healthy venv, start in project | `PIPENV_ACTIVE=1`, `VIRTUAL_ENV` set, `deactivate` defined | identical | +| healthy: project → elsewhere → back | activates → inactive → re-activates, stderr empty | identical | +| **project → unrelated `proj-archive` sibling** | ⚠️ stays active: `VIRTUAL_ENV= PIPENV_ACTIVE=1` | ✅ `VIRTUAL_ENV= PIPENV_ACTIVE=` | +| **project → `…/proj-archive/empty`** | ⚠️ still active | ✅ still inactive | +| **deep subdir *inside* the project** (no `Pipfile` there) | stays active | stays active (unchanged) | + +The boundary logic as a truth table (`stay` = keep virtualenv): + +| `pipfile_dir` | `PWD` | master | this branch | +|---|---|---|---| +| `/x/proj` | `/x/proj` | stay | stay | +| `/x/proj` | `/x/proj/src` | stay | stay | +| `/x/proj` | `/x/proj-archive` | ⚠️ stay | ✅ deactivate | +| `/x/proj` | `/x/projX` | ⚠️ stay | ✅ deactivate | +| `/` | `/tmp` | stay | stay | + +`zsh -n` passes on the plugin and the CI syntax sweep (`oh-my-zsh.sh`, `lib/*.zsh`, `plugins/*/*.plugin.zsh`, `plugins/*/_*`, `themes/*.zsh-theme`) is clean on this branch. + +## Other comments: + +If you would rather have these as two PRs, say the word and I will split commit 2 out onto its own branch — they are independent and each reverts cleanly on its own. They share a file and a function, which is why they are together here. + +The two new `[[ … ]]` operands and the `local project_dir` add no measurable startup cost: the guard is a shell builtin pattern match on variables that are already set, and the previously measured `pipenv --venv` call still happens exactly once per activation attempt as before. + +AI disclosure: this patch was prepared with the help of an AI coding agent (root-cause analysis, patch draft, and test harness). I reviewed every changed line and re-ran the tables above against both branches myself before submitting. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `146461f7c6d9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14021/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14021/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5f460c46997da178b3f73a8bb0b10a4c54856f11 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14021/tests/oracle.patch @@ -0,0 +1,36 @@ +diff --git a/plugins/pipenv/pipenv.plugin.zsh b/plugins/pipenv/pipenv.plugin.zsh +index 82ad2b75..8b943041 100644 +--- a/plugins/pipenv/pipenv.plugin.zsh ++++ b/plugins/pipenv/pipenv.plugin.zsh +@@ -56,19 +56,26 @@ if zstyle -T ':omz:plugins:pipenv' auto-shell; then + # deactivate shell if Pipfile doesn't exist and not in a subdir + if [[ ! -f "$PWD/Pipfile" ]]; then + if [[ "$PIPENV_ACTIVE" == 1 ]]; then +- if [[ "$PWD" != "$pipfile_dir"* ]]; then ++ # Compare whole path components: `$pipfile_dir"*` also matches unrelated ++ # siblings that merely start with the same text (…/proj -> …/proj-docs), ++ # which would keep the virtualenv active outside the project. ++ local project_dir="${pipfile_dir%/}" ++ if [[ "$PWD" != "$project_dir" && "$PWD" != "$project_dir"/* ]]; then + unset PIPENV_ACTIVE pipfile_dir + deactivate + fi + fi + fi + +- # activate the shell if Pipfile exists ++ # activate the shell if Pipfile exists and its virtualenv is usable + if [[ "$PIPENV_ACTIVE" != 1 ]]; then + if [[ -f "$PWD/Pipfile" ]]; then +- export pipfile_dir="$PWD" +- source "$(pipenv --venv)/bin/activate" +- export PIPENV_ACTIVE=1 ++ local venv_path ++ if venv_path="$(pipenv --venv 2>/dev/null)" && [[ -n "$venv_path" && -f "$venv_path/bin/activate" ]]; then ++ export pipfile_dir="$PWD" ++ source "$venv_path/bin/activate" ++ export PIPENV_ACTIVE=1 ++ fi + fi + fi + } diff --git a/tasks/ohmyzsh__ohmyzsh-14021/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14021/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..28dbccea5df3ad8079d2ed1187d679b93dc8fcf4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14021/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 146461f7c6d95f4ba1220559d66eb113418b40a8 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14021/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14021/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14021/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14024/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14024/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..59c1a16c2256f15de0df7a1312621bd147b28d0c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14024/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 146461f7c6d95f4ba1220559d66eb113418b40a8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 146461f7c6d95f4ba1220559d66eb113418b40a8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 146461f7c6d95f4ba1220559d66eb113418b40a8 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14024/instruction.md b/tasks/ohmyzsh__ohmyzsh-14024/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9f91816bf5cf72207bd38fd9eb7742a30811f77c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14024/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** fix(eza): pass an explicit WHEN value to --hyperlink + +## Description + +Since eza 0.23 `--hyperlink` is an option with an optional WHEN value +instead of a boolean flag, so a bare `--hyperlink` at the end of the +alias consumes the following argument: + + $ ll ./tmp + error: invalid value './tmp' for '--hyperlink []' + [possible values: always, auto, never] + +Pass `--hyperlink=auto` (mirroring how the plugin already handles +`--icons=auto`) when eza accepts it, and fall back to the bare flag on +older releases. + +Claude-Session: https://claude.ai/code/session_01FD5F6nyEXwHsqtH7eT3HeZ + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `146461f7c6d9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14024/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14024/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..412e9855adf889b8f86ba315221da7215f0d6dd3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14024/solution/patch.diff @@ -0,0 +1,20 @@ +diff --git a/plugins/eza/eza.plugin.zsh b/plugins/eza/eza.plugin.zsh +index 1ee86018..8809d8f3 100644 +--- a/plugins/eza/eza.plugin.zsh ++++ b/plugins/eza/eza.plugin.zsh +@@ -52,8 +52,13 @@ function _configure_eza() { + if [[ $_val ]]; then + _EZA_TAIL+=("--time-style='$_val'") + fi +- if zstyle -t ":omz:plugins:eza" "hyperlink"; then +- _EZA_TAIL+=("--hyperlink") ++ if zstyle -t ':omz:plugins:eza' 'hyperlink'; then ++ # eza >= 0.23 needs an explicit WHEN value ++ if command eza --hyperlink=auto --version &>/dev/null; then ++ _EZA_TAIL+=("--hyperlink=auto") ++ else ++ _EZA_TAIL+=("--hyperlink") ++ fi + fi + } + diff --git a/tasks/ohmyzsh__ohmyzsh-14024/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14024/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14024/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14024/task.toml b/tasks/ohmyzsh__ohmyzsh-14024/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f11fd6142e44cce97d3ed5d944a5c75e69dd1198 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14024/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14024" +description = "fix(eza): pass an explicit WHEN value to --hyperlink" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "146461f7c6d95f4ba1220559d66eb113418b40a8" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14024" +source_access = "auto" +built_at = "2026-11-16T16:09:57.016867+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f639e22a5aa208f9ff700067578ce54c3b7afb7000c2a7677edc64a8f076b30e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-29T00:36:05Z" +diff_format = "unified" +context_files = [ + "plugins/eza/eza.plugin.zsh", +] +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.966323+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ff7f138bd9df2f2c0c5639aaf8e83a1463a9fbbeaf554c71f007edbd79847218" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14024/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14024/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14024/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14024/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14024/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9f91816bf5cf72207bd38fd9eb7742a30811f77c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14024/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** fix(eza): pass an explicit WHEN value to --hyperlink + +## Description + +Since eza 0.23 `--hyperlink` is an option with an optional WHEN value +instead of a boolean flag, so a bare `--hyperlink` at the end of the +alias consumes the following argument: + + $ ll ./tmp + error: invalid value './tmp' for '--hyperlink []' + [possible values: always, auto, never] + +Pass `--hyperlink=auto` (mirroring how the plugin already handles +`--icons=auto`) when eza accepts it, and fall back to the bare flag on +older releases. + +Claude-Session: https://claude.ai/code/session_01FD5F6nyEXwHsqtH7eT3HeZ + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `146461f7c6d9`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14024/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14024/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..412e9855adf889b8f86ba315221da7215f0d6dd3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14024/tests/oracle.patch @@ -0,0 +1,20 @@ +diff --git a/plugins/eza/eza.plugin.zsh b/plugins/eza/eza.plugin.zsh +index 1ee86018..8809d8f3 100644 +--- a/plugins/eza/eza.plugin.zsh ++++ b/plugins/eza/eza.plugin.zsh +@@ -52,8 +52,13 @@ function _configure_eza() { + if [[ $_val ]]; then + _EZA_TAIL+=("--time-style='$_val'") + fi +- if zstyle -t ":omz:plugins:eza" "hyperlink"; then +- _EZA_TAIL+=("--hyperlink") ++ if zstyle -t ':omz:plugins:eza' 'hyperlink'; then ++ # eza >= 0.23 needs an explicit WHEN value ++ if command eza --hyperlink=auto --version &>/dev/null; then ++ _EZA_TAIL+=("--hyperlink=auto") ++ else ++ _EZA_TAIL+=("--hyperlink") ++ fi + fi + } + diff --git a/tasks/ohmyzsh__ohmyzsh-14024/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14024/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..28dbccea5df3ad8079d2ed1187d679b93dc8fcf4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14024/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 146461f7c6d95f4ba1220559d66eb113418b40a8 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14024/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14024/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14024/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14033/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14033/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..87783941613a7062c7404f7adaccf8bc36773495 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14033/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4b657407c98bbc8830ae66c2ac7ff3d737c55a83 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4b657407c98bbc8830ae66c2ac7ff3d737c55a83 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4b657407c98bbc8830ae66c2ac7ff3d737c55a83 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14033/instruction.md b/tasks/ohmyzsh__ohmyzsh-14033/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..91391011699ca67c93da14487822597626ac6719 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14033/instruction.md @@ -0,0 +1,65 @@ +# Issue + +**Title:** fix(git): restore `git_develop_branch` fallback in `gbds` + +## Description + +```zsh +local default_branch=$(git_main_branch) +(( ! $? )) || default_branch=$(git_develop_branch) +``` + +In zsh the exit status of `local var=$(cmd)` is the status of the `local` builtin, not of the command substitution — `local` succeeded, so `$?` is 0. The test therefore always passes, the `||` always short-circuits, and the `git_develop_branch` fallback is dead code. + +That matters because `git_main_branch` doesn't simply fail when it finds nothing. Lines 47-49 have it guess and report that it guessed: + +```zsh +# If no main branch was found, fall back to master but return error +echo master +return 1 +``` + +So in a repository whose default branch is `develop` or `dev`, with no `master` or `main` anywhere, `default_branch` is left as the string `master` — a branch that doesn't exist. Every `git merge-base master $branch` then fails, nothing is ever identified as squash-merged, and `gbds` deletes nothing and reports nothing. For a command whose job is deleting branches, silently doing nothing is a fairly unhelpful failure mode. + +Splitting the declaration from the assignment makes the status meaningful again. I used `||` directly rather than keeping the `$?` test, since that removes the need to reason about what `$?` refers to at that point — which is the trap the original fell into. + +Verified with a stub that mimics `git_main_branch`'s echo-`master`-and-return-1 behaviour: + +``` +before: master (fallback never ran) +after: develop +``` + +and with a stub that succeeds, confirming the success path still short-circuits and doesn't call `git_develop_branch`: + +``` +after: main +``` + +Repos that do have `main` or `master` are unaffected, so this only repairs the failing case rather than changing which branch is preferred. + +One thing I noticed while here but deliberately left alone to keep this reviewable: the same `local x=$(...)` followed by a `$?` test appears elsewhere in the tree and is probably worth a grep. + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Split the declaration from the assignment in `gbds` so a failing `git_main_branch` actually triggers the `git_develop_branch` fallback. + +## Other comments: + +AI-assisted: I've been using Oh My Zsh for years and wanted to contribute something back, so I used Claude to help audit the tree for bugs. This was one of the things it turned up. I've read the surrounding code, confirmed the behaviour myself on zsh 5.9.2, and can explain the change. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4b657407c98b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14033/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14033/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7180eb9801fd451507dd68e3dc58daa0b147ef96 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14033/solution/patch.diff @@ -0,0 +1,16 @@ +diff --git a/plugins/git/git.plugin.zsh b/plugins/git/git.plugin.zsh +index 16568f22..0b6b3ee1 100644 +--- a/plugins/git/git.plugin.zsh ++++ b/plugins/git/git.plugin.zsh +@@ -137,8 +137,9 @@ function gbda() { + # Copied and modified from James Roeder (jmaroeder) under MIT License + # https://github.com/jmaroeder/plugin-git/blob/216723ef4f9e8dde399661c39c80bdf73f4076c4/functions/gbda.fish + function gbds() { +- local default_branch=$(git_main_branch) +- (( ! $? )) || default_branch=$(git_develop_branch) ++ local default_branch ++ default_branch=$(git_main_branch) \ ++ || default_branch=$(git_develop_branch) + + git for-each-ref refs/heads/ "--format=%(refname:short)" | \ + while read branch; do diff --git a/tasks/ohmyzsh__ohmyzsh-14033/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14033/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14033/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14033/task.toml b/tasks/ohmyzsh__ohmyzsh-14033/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..da18086858cd4957a97d82fa9608cd52223b2f82 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14033/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14033" +description = "fix(git): restore `git_develop_branch` fallback in `gbds`" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "4b657407c98bbc8830ae66c2ac7ff3d737c55a83" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14033" +source_access = "auto" +built_at = "2026-11-16T16:09:57.013107+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e7f871449e559b862cfc3a8a76e31424bbe72821dbe4e524b5af855117bca53e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-08-30T17:12:19Z" +diff_format = "unified" +context_files = [ + "plugins/git/git.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.969266+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:fb268676157b9ab4495b8745d1e20bb2aed64e14116469d254197ac43de93a52" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14033/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14033/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14033/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14033/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14033/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..91391011699ca67c93da14487822597626ac6719 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14033/tests/instruction.md @@ -0,0 +1,65 @@ +# Issue + +**Title:** fix(git): restore `git_develop_branch` fallback in `gbds` + +## Description + +```zsh +local default_branch=$(git_main_branch) +(( ! $? )) || default_branch=$(git_develop_branch) +``` + +In zsh the exit status of `local var=$(cmd)` is the status of the `local` builtin, not of the command substitution — `local` succeeded, so `$?` is 0. The test therefore always passes, the `||` always short-circuits, and the `git_develop_branch` fallback is dead code. + +That matters because `git_main_branch` doesn't simply fail when it finds nothing. Lines 47-49 have it guess and report that it guessed: + +```zsh +# If no main branch was found, fall back to master but return error +echo master +return 1 +``` + +So in a repository whose default branch is `develop` or `dev`, with no `master` or `main` anywhere, `default_branch` is left as the string `master` — a branch that doesn't exist. Every `git merge-base master $branch` then fails, nothing is ever identified as squash-merged, and `gbds` deletes nothing and reports nothing. For a command whose job is deleting branches, silently doing nothing is a fairly unhelpful failure mode. + +Splitting the declaration from the assignment makes the status meaningful again. I used `||` directly rather than keeping the `$?` test, since that removes the need to reason about what `$?` refers to at that point — which is the trap the original fell into. + +Verified with a stub that mimics `git_main_branch`'s echo-`master`-and-return-1 behaviour: + +``` +before: master (fallback never ran) +after: develop +``` + +and with a stub that succeeds, confirming the success path still short-circuits and doesn't call `git_develop_branch`: + +``` +after: main +``` + +Repos that do have `main` or `master` are unaffected, so this only repairs the failing case rather than changing which branch is preferred. + +One thing I noticed while here but deliberately left alone to keep this reviewable: the same `local x=$(...)` followed by a `$?` test appears elsewhere in the tree and is probably worth a grep. + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Split the declaration from the assignment in `gbds` so a failing `git_main_branch` actually triggers the `git_develop_branch` fallback. + +## Other comments: + +AI-assisted: I've been using Oh My Zsh for years and wanted to contribute something back, so I used Claude to help audit the tree for bugs. This was one of the things it turned up. I've read the surrounding code, confirmed the behaviour myself on zsh 5.9.2, and can explain the change. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4b657407c98b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14033/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14033/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7180eb9801fd451507dd68e3dc58daa0b147ef96 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14033/tests/oracle.patch @@ -0,0 +1,16 @@ +diff --git a/plugins/git/git.plugin.zsh b/plugins/git/git.plugin.zsh +index 16568f22..0b6b3ee1 100644 +--- a/plugins/git/git.plugin.zsh ++++ b/plugins/git/git.plugin.zsh +@@ -137,8 +137,9 @@ function gbda() { + # Copied and modified from James Roeder (jmaroeder) under MIT License + # https://github.com/jmaroeder/plugin-git/blob/216723ef4f9e8dde399661c39c80bdf73f4076c4/functions/gbda.fish + function gbds() { +- local default_branch=$(git_main_branch) +- (( ! $? )) || default_branch=$(git_develop_branch) ++ local default_branch ++ default_branch=$(git_main_branch) \ ++ || default_branch=$(git_develop_branch) + + git for-each-ref refs/heads/ "--format=%(refname:short)" | \ + while read branch; do diff --git a/tasks/ohmyzsh__ohmyzsh-14033/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14033/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..78e93965801ce8cb1b90c7bd377403cf3bca2b87 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14033/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4b657407c98bbc8830ae66c2ac7ff3d737c55a83 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14033/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14033/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14033/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14035/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14035/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3199e9c539068a8bc8000aa597de876c4ee1adf6 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14035/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a5ecff7560b2e26f612032c632a12c75a3048bd0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a5ecff7560b2e26f612032c632a12c75a3048bd0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a5ecff7560b2e26f612032c632a12c75a3048bd0 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14035/instruction.md b/tasks/ohmyzsh__ohmyzsh-14035/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..57b99bed295bd105ea3eae848183920ec5cf2a7a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14035/instruction.md @@ -0,0 +1,66 @@ +# Issue + +**Title:** fix(ssh-agent): create screen/tmux symlink atomically + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +With `zstyle :omz:plugins:ssh-agent agent-forwarding yes`, opening a tmux window +that starts several panes at once prints one or more of these to stderr: + +``` +ln: /tmp/ssh-agent--screen: File exists +``` + +The symlink still ends up correct, so this is cosmetic, but it is noise on every +multi-pane startup and it looks like a real failure. + +**Cause.** The symlink block runs on *every* shell startup — the guard above it +(`[[ ! -L "$SSH_AUTH_SOCK" ]]`) tests the source socket, not the destination, so +the link is torn down and rebuilt each time. `ln -sf` is not an atomic swap: it +unlinks the destination, then calls `symlink()`. Two shells starting at the same +moment interleave those steps — A unlinks, B unlinks (already gone), A creates, +B's `symlink()` returns `EEXIST`. + +**Fix.** Stage the link under a PID-unique name and move it into place. +`rename(2)` replaces the destination atomically, so concurrent shells can never +collide, and the last writer still wins with a correct link. + +## Other comments: + +Measured on macOS 15 (Darwin 25.6.0), zsh 5.9, 200 concurrent invocations of each +variant (8 at a time, 25 rounds): + +| variant | `File exists` errors | +| --- | --- | +| current `ln -sf` | 82 / 200 | +| this patch | 0 / 200 | + +Also reproduced end-to-end with real shell startups before the fix — 60 startups +of my own interactive zsh, 6 concurrent at a time, produced 22 errors; the same +60 run strictly sequentially produced 0, isolating concurrency as the trigger. + +After the patched run the link resolves to the correct socket and no `.$$` +staging files are left behind (verified with `find`, against a positive control). + +No behavior change for the single-shell case. + +AI disclosure: the diagnosis, the A/B benchmark, and this description were +produced with Claude (Anthropic) assisting; I reviewed and tested the result. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a5ecff7560b2`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14035/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14035/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e5403667cc59a46c1bd953c5e1cbc060eac454ff --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14035/solution/patch.diff @@ -0,0 +1,25 @@ +diff --git a/plugins/ssh-agent/ssh-agent.plugin.zsh b/plugins/ssh-agent/ssh-agent.plugin.zsh +index 83548648..4517242e 100644 +--- a/plugins/ssh-agent/ssh-agent.plugin.zsh ++++ b/plugins/ssh-agent/ssh-agent.plugin.zsh +@@ -101,10 +101,18 @@ if zstyle -t :omz:plugins:ssh-agent agent-forwarding \ + && [[ -n "$SSH_AUTH_SOCK" ]]; then + if [[ ! -L "$SSH_AUTH_SOCK" ]]; then + if [[ -n "$TERMUX_VERSION" ]]; then +- ln -sf "$SSH_AUTH_SOCK" "$PREFIX"/tmp/ssh-agent-$USERNAME-screen ++ _omz_ssh_agent_link="$PREFIX"/tmp/ssh-agent-$USERNAME-screen + else +- ln -sf "$SSH_AUTH_SOCK" /tmp/ssh-agent-$USERNAME-screen ++ _omz_ssh_agent_link=/tmp/ssh-agent-$USERNAME-screen + fi ++ # `ln -sf` unlinks the old symlink and then creates the new one: two ++ # syscalls, no atomic swap. Shells starting concurrently (a tmux window ++ # opening several panes at once) interleave those steps and all but one ++ # fail with "ln: ...: File exists". Stage the link under a PID-unique ++ # name and move it into place, since rename(2) is atomic. ++ command ln -sf "$SSH_AUTH_SOCK" "$_omz_ssh_agent_link.$$" \ ++ && command mv -f "$_omz_ssh_agent_link.$$" "$_omz_ssh_agent_link" ++ unset _omz_ssh_agent_link + fi + else + _start_agent diff --git a/tasks/ohmyzsh__ohmyzsh-14035/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14035/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14035/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14035/task.toml b/tasks/ohmyzsh__ohmyzsh-14035/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ff5b0c9bfcd49acdec456214aff937de9fc29eb2 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14035/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14035" +description = "fix(ssh-agent): create screen/tmux symlink atomically" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "a5ecff7560b2e26f612032c632a12c75a3048bd0" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14035" +source_access = "auto" +built_at = "2026-11-16T16:09:57.009988+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ff56ac73867d501b46f53ebc7c46bc36811fea334dbcd81de54a8fa4cc315157" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-04T11:19:11Z" +diff_format = "unified" +context_files = [ + "plugins/ssh-agent/ssh-agent.plugin.zsh", +] +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.970214+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:7e02fa40f70f128da052c3fe3b504b52b92fbf1f3dc394ca1ec4ba7fd5baa272" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14035/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14035/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14035/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14035/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14035/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..57b99bed295bd105ea3eae848183920ec5cf2a7a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14035/tests/instruction.md @@ -0,0 +1,66 @@ +# Issue + +**Title:** fix(ssh-agent): create screen/tmux symlink atomically + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +With `zstyle :omz:plugins:ssh-agent agent-forwarding yes`, opening a tmux window +that starts several panes at once prints one or more of these to stderr: + +``` +ln: /tmp/ssh-agent--screen: File exists +``` + +The symlink still ends up correct, so this is cosmetic, but it is noise on every +multi-pane startup and it looks like a real failure. + +**Cause.** The symlink block runs on *every* shell startup — the guard above it +(`[[ ! -L "$SSH_AUTH_SOCK" ]]`) tests the source socket, not the destination, so +the link is torn down and rebuilt each time. `ln -sf` is not an atomic swap: it +unlinks the destination, then calls `symlink()`. Two shells starting at the same +moment interleave those steps — A unlinks, B unlinks (already gone), A creates, +B's `symlink()` returns `EEXIST`. + +**Fix.** Stage the link under a PID-unique name and move it into place. +`rename(2)` replaces the destination atomically, so concurrent shells can never +collide, and the last writer still wins with a correct link. + +## Other comments: + +Measured on macOS 15 (Darwin 25.6.0), zsh 5.9, 200 concurrent invocations of each +variant (8 at a time, 25 rounds): + +| variant | `File exists` errors | +| --- | --- | +| current `ln -sf` | 82 / 200 | +| this patch | 0 / 200 | + +Also reproduced end-to-end with real shell startups before the fix — 60 startups +of my own interactive zsh, 6 concurrent at a time, produced 22 errors; the same +60 run strictly sequentially produced 0, isolating concurrency as the trigger. + +After the patched run the link resolves to the correct socket and no `.$$` +staging files are left behind (verified with `find`, against a positive control). + +No behavior change for the single-shell case. + +AI disclosure: the diagnosis, the A/B benchmark, and this description were +produced with Claude (Anthropic) assisting; I reviewed and tested the result. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a5ecff7560b2`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14035/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14035/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e5403667cc59a46c1bd953c5e1cbc060eac454ff --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14035/tests/oracle.patch @@ -0,0 +1,25 @@ +diff --git a/plugins/ssh-agent/ssh-agent.plugin.zsh b/plugins/ssh-agent/ssh-agent.plugin.zsh +index 83548648..4517242e 100644 +--- a/plugins/ssh-agent/ssh-agent.plugin.zsh ++++ b/plugins/ssh-agent/ssh-agent.plugin.zsh +@@ -101,10 +101,18 @@ if zstyle -t :omz:plugins:ssh-agent agent-forwarding \ + && [[ -n "$SSH_AUTH_SOCK" ]]; then + if [[ ! -L "$SSH_AUTH_SOCK" ]]; then + if [[ -n "$TERMUX_VERSION" ]]; then +- ln -sf "$SSH_AUTH_SOCK" "$PREFIX"/tmp/ssh-agent-$USERNAME-screen ++ _omz_ssh_agent_link="$PREFIX"/tmp/ssh-agent-$USERNAME-screen + else +- ln -sf "$SSH_AUTH_SOCK" /tmp/ssh-agent-$USERNAME-screen ++ _omz_ssh_agent_link=/tmp/ssh-agent-$USERNAME-screen + fi ++ # `ln -sf` unlinks the old symlink and then creates the new one: two ++ # syscalls, no atomic swap. Shells starting concurrently (a tmux window ++ # opening several panes at once) interleave those steps and all but one ++ # fail with "ln: ...: File exists". Stage the link under a PID-unique ++ # name and move it into place, since rename(2) is atomic. ++ command ln -sf "$SSH_AUTH_SOCK" "$_omz_ssh_agent_link.$$" \ ++ && command mv -f "$_omz_ssh_agent_link.$$" "$_omz_ssh_agent_link" ++ unset _omz_ssh_agent_link + fi + else + _start_agent diff --git a/tasks/ohmyzsh__ohmyzsh-14035/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14035/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c584d8a475d93860d45ccd22705609c83d6b16bc --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14035/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a5ecff7560b2e26f612032c632a12c75a3048bd0 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14035/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14035/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14035/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14037/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14037/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..88e359af8c23c92832cbaa2d237edeec7ac47ce8 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14037/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3f84a2ae4ab63343890ff90efca6d18b7292dd0f 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3f84a2ae4ab63343890ff90efca6d18b7292dd0f \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3f84a2ae4ab63343890ff90efca6d18b7292dd0f \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14037/instruction.md b/tasks/ohmyzsh__ohmyzsh-14037/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c37ec78c6043484cda6232a6d719129b3c092bab --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14037/instruction.md @@ -0,0 +1,55 @@ +# Issue + +**Title:** feat(shopify): add plugin for Shopify CLI + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Screenshot + +image + + +## Changes: + +While working on the Shopify theme for [CommitGoods.com](https://commitgoods.com/) I kept wishing I had the +same shortcuts I have for everything else in my shell, so I put them in a plugin. + +It adds completion for the Shopify CLI, one alias (`shop`), and a few helpers +that pick the right command for whichever kind of project you are in — `shopd` +runs `theme dev`, `app dev` or `hydrogen dev` depending on the directory. The +CLI ships no completion generator of its own, so `_shopify` is generated from +`shopify commands --json` and checked in, the way `cdk` and `terraform` already +do. It targets Shopify CLI 4.x. + +It also asks for confirmation before three irreversible commands: +`theme push --live`, `theme delete`, and `app deploy --allow-deletes`. That is +skipped when `--force` is set or stdin is not a terminal, so scripts and CI are +unaffected, and it can be turned off with a zstyle. + +## Other comments: + +Only one alias, `shop`, on the guide's preference for one generic alias over +many specific ones. It collides with nothing in the tree and is not a real +command. + +`zsh -n` passes on both files. I tested the completion and the confirmation +prompt by hand across theme, app and Hydrogen projects. + +Written with Claude Code; I verified the CLI surface and tested it myself. +Testers welcome, especially on apps and Hydrogen — my own use here is themes. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3f84a2ae4ab6`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14037/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14037/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cc9b1aea08e6acf7a054704f3c7d03982aedc737 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14037/solution/patch.diff @@ -0,0 +1,2378 @@ +diff --git a/plugins/shopify/README.md b/plugins/shopify/README.md +new file mode 100644 +index 00000000..e07faa8f +--- /dev/null ++++ b/plugins/shopify/README.md +@@ -0,0 +1,112 @@ ++# Shopify CLI plugin ++ ++This plugin adds aliases, helper functions and completion for the ++[Shopify CLI](https://shopify.dev/docs/api/shopify-cli). ++ ++To use it, add `shopify` to the plugins array in your zshrc file: ++ ++```zsh ++plugins=(... shopify) ++``` ++ ++## Requirements ++ ++[Shopify CLI](https://shopify.dev/docs/api/shopify-cli) 4.0 or newer, installed ++and on your `PATH`. The plugin does nothing if it is not: ++ ++```zsh ++npm install -g @shopify/cli ++# or ++brew tap shopify/shopify && brew install shopify-cli ++``` ++ ++## Aliases ++ ++| Alias | Command | Description | ++| :----- | :-------- | :--------------------- | ++| `shop` | `shopify` | The Shopify CLI itself | ++ ++## Functions ++ ++| Function | Description | ++| :------------- | :--------------------------------------------------------------------------------- | ++| `shopd` | Runs `theme dev`, `app dev` or `hydrogen dev`, whichever fits the current project | ++| `shopi` | Shows what the current project is connected to | ++| `shopify_here` | Prints the kind of Shopify project you are in and the commands worth running in it | ++| `shopify` | Wraps the CLI to confirm before irreversible commands. See Settings | ++ ++`shopd` and `shopi` work out which topic applies by looking at the project you ++are standing in, so you do not have to remember whether this directory is a ++theme, an app or a Hydrogen storefront. They complete like the command they ++stand in for, so in a theme `shopd --` offers the flags of ++`shopify theme dev`. ++ ++## Completion ++ ++Every command completes with a description of what it does, at every level, and ++so do their flags, short forms and allowed values. `--environment` completes ++from the `[environments.*]` sections of your local `shopify.theme.toml` or ++`shopify.app.toml`. ++ ++The Shopify CLI ships no completion generator of its own, so `_shopify` is ++generated from `shopify commands --json` and kept in this repository. It targets ++Shopify CLI 4.x. ++ ++## Settings ++ ++Set these with `zstyle` in your zshrc, before Oh My Zsh is sourced. ++ ++### Confirming destructive commands ++ ++```zsh ++zstyle ':omz:plugins:shopify' confirm-destructive no ++``` ++ ++By default the plugin asks for confirmation before three irreversible ++operations: ++ ++- `shopify theme push` with `--live`/`-l` or `--publish`/`-p`, which overwrites ++ or publishes the live storefront ++- `shopify theme delete`, which the CLI's own help describes as impossible to ++ undo ++- `shopify app deploy --allow-deletes`, which can permanently remove extensions ++ ++Nothing else is intercepted, and the prompt is skipped when the command already ++carries `--force`/`-f` or when stdin is not a terminal, so scripts, pipelines ++and CI are unaffected. Set the style to `no` to turn the prompt off entirely. ++ ++### Completing theme IDs ++ ++```zsh ++zstyle ':omz:plugins:shopify' dynamic-theme-completion yes ++``` ++ ++Off by default. When enabled, `--theme` is completed from ++`shopify theme list --json`, showing each theme's name and role next to its ID ++instead of making you copy IDs by hand. It is opt-in because it runs the CLI and ++makes a network call when you press Tab, and because it needs you to ++be authenticated. Results are cached for five minutes. ++ ++### Disabling the aliases ++ ++This works for every Oh My Zsh plugin: ++ ++```zsh ++zstyle ':omz:plugins:shopify' aliases no ++``` ++ ++## Caveats ++ ++- `shopify` is a shell function here. Run `command shopify` to reach the binary ++ directly. ++- When a project has its own copy of the CLI in `node_modules/.bin/shopify`, ++ that one is used in preference to the global install. App and Hydrogen ++ projects normally pin the CLI in `package.json`, and running a different ++ global version against them is a common source of confusing errors. ++- `--password` and `--store-password` are unrelated, and you often need both. ++ `--password` is the CLI's own authentication token, from the Theme Access app ++ or the Admin API. `--store-password` is the password for a ++ password-protected storefront. ++- `shopify theme push` deletes remote files that are missing locally, and ++ `shopify theme pull` deletes local files that are missing remotely, unless you ++ pass `--nodelete`/`-n`. The plugin does not prompt for these. +diff --git a/plugins/shopify/_shopify b/plugins/shopify/_shopify +new file mode 100644 +index 00000000..2f6d6ca2 +--- /dev/null ++++ b/plugins/shopify/_shopify +@@ -0,0 +1,2045 @@ ++#compdef shopify ++ ++# Completion for the Shopify CLI. https://shopify.dev/docs/api/shopify-cli ++# ++# Targets Shopify CLI 4.x. The CLI has no `completion`/`autocomplete` command, ++# so this is generated from `shopify commands --json` and kept here. Nothing ++# runs the CLI at completion time unless theme completion is enabled below. ++ ++# Environment names from the project's TOML config. Offline, always enabled. ++_shopify_environments() { ++ setopt localoptions extendedglob ++ local -a envs ++ local file line ++ # (#b) backreferences set $match, which would otherwise be left global. ++ local MATCH MBEGIN MEND ++ local -a match mbegin mend ++ for file in shopify.theme.toml shopify.app.toml; do ++ [[ -r "$file" ]] || continue ++ for line in ${(f)"$(< $file)"}; do ++ [[ $line == (#b)[[:space:]]#\[environments\.([^]]##)\]* ]] && envs+=("$match[1]") ++ done ++ done ++ (( $#envs )) || return 1 ++ _describe -t environments 'environment' envs ++} ++ ++# Theme IDs, described by name and role. Off by default: needs auth and makes a ++# network call on TAB. Enable with: ++# zstyle ':omz:plugins:shopify' dynamic-theme-completion yes ++_shopify_themes() { ++ zstyle -t ':omz:plugins:shopify' dynamic-theme-completion || return 1 ++ ++ local key="${${PWD:A}//\//-}" ++ local cache_file="$ZSH_CACHE_DIR/shopify-themes${key: -100}" ++ local -a themes fresh ++ local json split entry id name role ++ # $match and friends are set by =~ and would otherwise be left global. ++ local MATCH MBEGIN MEND ++ local -a match mbegin mend ++ local nl=$'\n' ++ ++ # Reuse the cached list for five minutes. ++ fresh=(${cache_file}(Nms-300)) ++ if (( $#fresh )); then ++ themes=("${(@f)$(< "$cache_file")}") ++ else ++ json="$(shopify theme list --json 2>/dev/null)" || return 1 ++ split="${json//\{/$nl}" ++ for entry in ${(f)split}; do ++ id="" name="" role="" ++ [[ $entry =~ '"id":[[:space:]]*([0-9]+)' ]] && id=$match[1] ++ [[ $entry =~ '"name":[[:space:]]*"([^"]*)"' ]] && name=$match[1] ++ [[ $entry =~ '"role":[[:space:]]*"([^"]*)"' ]] && role=$match[1] ++ [[ -n $id ]] || continue ++ themes+=("${id}:${name}${role:+ (${role})}") ++ done ++ (( $#themes )) || return 1 ++ print -rl -- $themes > "$cache_file" ++ fi ++ ++ _describe -t shopify-themes 'theme' themes ++} ++ ++_shopify__app__build() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--skip-dependencies-installation[Skips the installation of dependencies]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__bulk__cancel() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--id=[The bulk operation ID to cancel (numeric ID or full GID)]:id:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '(-s --store)'{-s,--store}'=[The store domain]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__bulk__execute() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--output-file=[The file path where results should be written if --watch is specified]:output-file:' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(-q --query)'{-q,--query}'=[The GraphQL query or mutation to run as a bulk operation]:query:' \ ++ '--query-file=[Path to a file containing the GraphQL query or mutation]:query-file:' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '(-s --store)'{-s,--store}'=[The store domain]:store:' \ ++ '(--variable-file -v --variables)--variable-file=[Path to a file containing GraphQL variables in JSONL format (one JSON...]:variable-file:' \ ++ *''{-v,--variables}'=[The values for any GraphQL variables in your mutation, in JSON format]:variables:' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '--version=[The API version to use for the bulk operation]:version:' \ ++ '--watch[Wait for bulk operation results before exiting]' ++} ++ ++_shopify__app__bulk__status() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--id=[The bulk operation ID (numeric ID or full GID)]:id:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '(-s --store)'{-s,--store}'=[The store domain]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__bulk() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'cancel:Cancel a bulk operation' ++ 'execute:Execute bulk operations' ++ 'status:Check the status of bulk operations' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app bulk command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ cancel) _shopify__app__bulk__cancel && ret=0 ;; ++ execute) _shopify__app__bulk__execute && ret=0 ;; ++ status) _shopify__app__bulk__status && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__app__config__link() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '(--file-name -c --config)--file-name=[The name of the app configuration file to create or overwrite]:file-name:' \ ++ '--force[Overwrite an existing configuration file without prompting]' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__config__pull() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__config__use() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '--client-id=[The Client ID of your app]:client-id:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '*:file:_files' ++} ++ ++_shopify__app__config__validate() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__config() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'link:Fetch your app configuration from the Developer Dashboard' ++ 'pull:Refresh an already-linked app configuration without prompts' ++ 'use:Activate an app configuration' ++ 'validate:Validate your app configuration and extensions' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app config command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ link) _shopify__app__config__link && ret=0 ;; ++ pull) _shopify__app__config__pull && ret=0 ;; ++ use) _shopify__app__config__use && ret=0 ;; ++ validate) _shopify__app__config__validate && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__app__deploy() { ++ _arguments -s -S \ ++ '--allow-deletes[Allows removing extensions and configuration without requiring user...]' \ ++ '--allow-updates[Allows adding and updating extensions and configuration without requiring...]' \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--message=[Optional message that will be associated with this version]:message:' \ ++ '--no-build[Use with caution\: Skips building any elements of the app that require...]' \ ++ '--no-color[Disable color output]' \ ++ '(--no-release --allow-updates --allow-deletes)--no-release[Creates a version but doesn'\''t release it - it'\''s not made available to...]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--source-control-url=[URL associated with the new app version]:source-control-url:' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '--version=[Optional version tag that will be associated with this app version]:version:' ++} ++ ++_shopify__app__dev__clean() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__dev() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'clean:Cleans up the dev preview from the selected store' ++ ) ++ ++ _arguments -s -C \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '--checkout-cart-url=[Resource URL for checkout UI extension]:checkout-cart-url:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--install-mkcert[Install and use mkcert to generate localhost certificates when...]' \ ++ '--localhost-port=[Port to use for localhost]:localhost-port:' \ ++ '--no-color[Disable color output]' \ ++ '--no-update[Uses the app URL from the toml file instead an autogenerated URL for dev]' \ ++ '--notify=[The file path or URL]:notify:_files' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--skip-dependencies-installation[Skips the installation of dependencies]' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--store-password=[The password for storefronts with password protection]:store-password:' \ ++ '--subscription-product-url=[Resource URL for subscription UI extension]:subscription-product-url:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the theme app extension host theme]:theme:' \ ++ '--theme-app-extension-port=[Local port of the theme app extension development server]:theme-app-extension-port:' \ ++ '--tunnel-url=[Use a custom tunnel, it must be running before executing dev]:tunnel-url:' \ ++ '(--use-localhost --tunnel-url)--use-localhost[Service entry point will listen to localhost]' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app dev command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ clean) _shopify__app__dev__clean && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__app__env__pull() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--env-file=[Specify an environment file to update if the update flag is set]:env-file:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__env__show() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__env() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'pull:Pull app and extensions environment variables' ++ 'show:Display app and extensions environment variables' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app env command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ pull) _shopify__app__env__pull && ret=0 ;; ++ show) _shopify__app__env__show && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__app__execute() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--output-file=[The file name where results should be written, instead of STDOUT]:output-file:' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(-q --query)'{-q,--query}'=[The GraphQL query or mutation, as a string]:query:' \ ++ '--query-file=[Path to a file containing the GraphQL query or mutation]:query-file:' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store to execute against]:store:' \ ++ '(--variable-file -v --variables)--variable-file=[Path to a file containing GraphQL variables in JSON format]:variable-file:' \ ++ '(-v --variables --variable-file)'{-v,--variables}'=[The values for any GraphQL variables in your query or mutation, in JSON...]:variables:' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '--version=[The API version to use for the query or mutation]:version:' ++} ++ ++_shopify__app__function__build() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your function directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__function__info() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your function directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__function__replay() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '(-l --log)'{-l,--log}'=[Specifies a log identifier to replay instead of selecting from a list]:log:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your function directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '(-w --watch)'{-w,--watch}'[Re-run the function when the source code changes]' ++} ++ ++_shopify__app__function__run() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '(-e --export)'{-e,--export}'=[Name of the WebAssembly export to invoke]:export:' \ ++ '(-i --input)'{-i,--input}'=[The input JSON to pass to the function]:input:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your function directory]:path:_files -/' \ ++ '--profile[Generate a WebAssembly performance profile for the function run]' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__function__schema() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your function directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--stdout[Output the schema to stdout instead of writing to a file]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__function__typegen() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your function directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__function() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'build:Compile a function to wasm' ++ 'info:Print basic information about your function' ++ 'replay:Replays a function run from an app log' ++ 'run:Run a function locally for testing' ++ 'schema:Fetch the latest GraphQL schema for a function' ++ 'typegen:Generate GraphQL types for a function' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app function command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ build) _shopify__app__function__build && ret=0 ;; ++ info) _shopify__app__function__info && ret=0 ;; ++ replay) _shopify__app__function__replay && ret=0 ;; ++ run) _shopify__app__function__run && ret=0 ;; ++ schema) _shopify__app__function__schema && ret=0 ;; ++ typegen) _shopify__app__function__typegen && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__app__generate__extension() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--flavor=[Choose a starting template for your extension, where applicable]:flavor:(vanilla-js react typescript typescript-react wasm rust)' \ ++ '(-n --name)'{-n,--name}'=[name of your Extension]:name:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '(-t --template)'{-t,--template}'=[Extension template]:template:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__generate() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'extension:Generate a new app Extension' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app generate command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ extension) _shopify__app__generate__extension && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__app__graphiql() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '--port=[Local port for the GraphiQL server]:port:' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store to open GraphiQL against]:store:' \ ++ '(-v --variables)'{-v,--variables}'=[The values for any GraphQL variables in your query or mutation, in JSON...]:variables:' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '--version=[The API version to use in GraphiQL]:version:' ++} ++ ++_shopify__app__import_custom_data_definitions() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--include-existing[Include existing declared definitions in the output]' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__import_extensions() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__info() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '--web-env[Outputs environment variables necessary for running and deploying web/]' ++} ++ ++_shopify__app__init() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '--client-id=[The Client ID of your app]:client-id:' \ ++ '--flavor=[Which flavor of the given template to use]:flavor:' \ ++ '(-n --name)'{-n,--name}'=[The name for the new app]:name:' \ ++ '--no-color[Disable color output]' \ ++ '(--organization-id --client-id)--organization-id=[The organization ID]:organization-id:' \ ++ '(-d --package-manager)'{-d,--package-manager}'=[]:package-manager:(npm yarn pnpm bun)' \ ++ '(-p --path)'{-p,--path}'=[]:path:_files -/' \ ++ '--template=[The app template]:template:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__logs__sources() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__logs() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'sources:Print out a list of sources that may be used with the logs command' ++ ) ++ ++ _arguments -s -C \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ *'--source=[Filters output to the specified log source]:source:' \ ++ '--status=[Filters output to the specified status (success or failure)]:status:(success failure)' \ ++ *''{-s,--store}'=[Store URL]:store:' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app logs command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ sources) _shopify__app__logs__sources && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__app__release() { ++ _arguments -s -S \ ++ '--allow-deletes[Allows removing extensions and configuration without requiring user...]' \ ++ '--allow-updates[Allows adding and updating extensions and configuration without requiring...]' \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '--version=[The name of the app version to release]:version:' ++} ++ ++_shopify__app__versions__list() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__versions() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List deployed versions of your app' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app versions command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _shopify__app__versions__list && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__app__webhook__trigger() { ++ _arguments -s -S \ ++ '--address=[The URL where the webhook payload should be sent]:address:' \ ++ '--api-version=[The API Version of the webhook topic]:api-version:' \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '--client-secret=[Your app'\''s client secret]:client-secret:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--delivery-method=[Method chosen to deliver the topic payload]:delivery-method:(http google-pub-sub event-bridge)' \ ++ '--help[This help]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--topic=[The requested webhook topic]:topic:' ++} ++ ++_shopify__app__webhook() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'trigger:Trigger delivery of a sample webhook topic payload to a designated address' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app webhook command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ trigger) _shopify__app__webhook__trigger && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__app() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'build:Build the app, including extensions' ++ 'bulk:Run bulk operations' ++ 'config:Manage app configuration files' ++ 'deploy:Deploy your Shopify app' ++ 'dev:Run the app' ++ 'env:Manage app environment variables' ++ 'execute:Execute GraphQL queries and mutations' ++ 'function:Work with Shopify Functions' ++ 'generate:Scaffold app extensions' ++ 'graphiql:Open a local GraphiQL UI for your app and store' ++ 'import-custom-data-definitions:Import metafield and metaobject definitions' ++ 'import-extensions:Import dashboard-managed extensions into your app' ++ 'info:Print basic information about your app and extensions' ++ 'init:Create a new app project' ++ 'logs:Stream detailed logs for your Shopify app' ++ 'release:Release an app version' ++ 'versions:Work with deployed app versions' ++ 'webhook:Trigger sample webhooks' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ build) _shopify__app__build && ret=0 ;; ++ bulk) _shopify__app__bulk && ret=0 ;; ++ config) _shopify__app__config && ret=0 ;; ++ deploy) _shopify__app__deploy && ret=0 ;; ++ dev) _shopify__app__dev && ret=0 ;; ++ env) _shopify__app__env && ret=0 ;; ++ execute) _shopify__app__execute && ret=0 ;; ++ function) _shopify__app__function && ret=0 ;; ++ generate) _shopify__app__generate && ret=0 ;; ++ graphiql) _shopify__app__graphiql && ret=0 ;; ++ import-custom-data-definitions) _shopify__app__import_custom_data_definitions && ret=0 ;; ++ import-extensions) _shopify__app__import_extensions && ret=0 ;; ++ info) _shopify__app__info && ret=0 ;; ++ init) _shopify__app__init && ret=0 ;; ++ logs) _shopify__app__logs && ret=0 ;; ++ release) _shopify__app__release && ret=0 ;; ++ versions) _shopify__app__versions && ret=0 ;; ++ webhook) _shopify__app__webhook && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__auth__login() { ++ _arguments -s -S \ ++ '--alias=[Alias of an existing session you want to use]:alias:' ++} ++ ++_shopify__auth__logout() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify__auth() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'login:Logs you in to your Shopify account' ++ 'logout:Logs you out of the Shopify account or Partner account and store' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'auth command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ login) _shopify__auth__login && ret=0 ;; ++ logout) _shopify__auth__logout && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__commands() { ++ _arguments -s -S \ ++ *''{-c,--columns}'=[Only show provided columns (comma-separated)]:columns:(id plugin summary type)' \ ++ '--deprecated[Show deprecated commands]' \ ++ '(-x --extended --tree)'{-x,--extended}'[Show extra columns]' \ ++ '--hidden[Show hidden commands]' \ ++ '--json[Format output as json]' \ ++ '(--no-truncate --tree)--no-truncate[Do not truncate output]' \ ++ '(--sort --tree)--sort=[Property to sort by]:sort:(id plugin summary type)' \ ++ '--tree[Show tree of commands]' ++} ++ ++_shopify__config__autocorrect__off() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify__config__autocorrect__on() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify__config__autocorrect__status() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify__config__autocorrect() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'off:Disable autocorrect' ++ 'on:Enable autocorrect' ++ 'status:Check whether autocorrect is enabled or disabled' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'config autocorrect command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ off) _shopify__config__autocorrect__off && ret=0 ;; ++ on) _shopify__config__autocorrect__on && ret=0 ;; ++ status) _shopify__config__autocorrect__status && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__config__autoupgrade__off() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify__config__autoupgrade__on() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify__config__autoupgrade__status() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify__config__autoupgrade() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'off:Disable automatic upgrades for Shopify CLI' ++ 'on:Enable automatic upgrades for Shopify CLI' ++ 'status:Check whether auto-upgrade is enabled, disabled, or not yet configured' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'config autoupgrade command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ off) _shopify__config__autoupgrade__off && ret=0 ;; ++ on) _shopify__config__autoupgrade__on && ret=0 ;; ++ status) _shopify__config__autoupgrade__status && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__config() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'autocorrect:Enable or disable command autocorrect' ++ 'autoupgrade:Enable or disable automatic upgrades' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'config command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ autocorrect) _shopify__config__autocorrect && ret=0 ;; ++ autoupgrade) _shopify__config__autoupgrade && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__doc__fetch() { ++ _arguments -s -S \ ++ '--no-color[Disable color output]' \ ++ '--output=[Write the document to this file path instead of printing it to stdout]:output:' \ ++ '--url=[The shopify.dev URL to fetch]:url:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__doc__search() { ++ _arguments -s -S \ ++ '--api-name=[Limit results to a specific API (for example\: admin, storefront, hydrogen,...]:api-name:' \ ++ '--api-version=[Limit results to a specific API version (for example\: 2025-10, latest,...]:api-version:' \ ++ '--no-color[Disable color output]' \ ++ '--query=[The search query]:query:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__doc() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'fetch:Download a complete document from shopify.dev' ++ 'search:Query the shopify.dev vector store and print the most relevant...' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'doc command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ fetch) _shopify__doc__fetch && ret=0 ;; ++ search) _shopify__doc__search && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__help() { ++ _arguments -s -S \ ++ '(-n --nested-commands)'{-n,--nested-commands}'[Include all nested commands in the output]' \ ++ '*:file:_files' ++} ++ ++_shopify__hydrogen__build() { ++ _arguments -s -S \ ++ '--bundle-stats[Show a bundle size summary after building]' \ ++ '--codegen[Automatically generates GraphQL types for your project’s Storefront API...]' \ ++ '--codegen-config-path=[Specifies a path to a codegen configuration file]:codegen-config-path:' \ ++ '--disable-route-warning[Disables any warnings about missing standard routes]' \ ++ '--entry=[Entry file for the worker]:entry:_files' \ ++ '--force-client-sourcemap[Client sourcemapping is avoided by default because it makes backend code...]' \ ++ '--lockfile-check[Checks that there is exactly one valid lockfile in the project]' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '--sourcemap[Controls whether server sourcemaps are generated]' \ ++ '--watch[Watches for changes and rebuilds the project writing output to disk]' ++} ++ ++_shopify__hydrogen__check() { ++ _arguments -s -S \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '*:file:_files' ++} ++ ++_shopify__hydrogen__codegen() { ++ _arguments -s -S \ ++ '--codegen-config-path=[Specify a path to a codegen configuration file]:codegen-config-path:' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '--watch[Watch the project for changes to update types on file save]' ++} ++ ++_shopify__hydrogen__customer_account_push() { ++ _arguments -s -S \ ++ '--dev-origin=[The development domain of your application]:dev-origin:' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '--relative-logout-uri=[The relative url of allowed url that will be redirected to post-logout for...]:relative-logout-uri:' \ ++ '--relative-redirect-uri=[The relative url of allowed callback url for Customer Account API OAuth flow]:relative-redirect-uri:' \ ++ '--storefront-id=[The id of the storefront the configuration should be pushed to]:storefront-id:' ++} ++ ++_shopify__hydrogen__debug__cpu() { ++ _arguments -s -S \ ++ '--entry=[Entry file for the worker]:entry:_files' \ ++ '--output=[Specify a path to generate the profile file]:output:' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' ++} ++ ++_shopify__hydrogen__debug() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'cpu:Builds and profiles the server startup time the app' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'hydrogen debug command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ cpu) _shopify__hydrogen__debug__cpu && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__hydrogen__deploy() { ++ _arguments -s -S \ ++ '--assets-dir=[Directory containing the client assets to deploy, relative to the project...]:assets-dir:' \ ++ '--auth-bypass-token[Generate an authentication bypass token, which can be used to perform...]' \ ++ '--auth-bypass-token-duration=[Specify the duration (in hours) up to 12 hours for the authentication...]:auth-bypass-token-duration:' \ ++ '--build-command=[Specify a build command to run before deploying]:build-command:' \ ++ '--entry=[Entry file for the worker]:entry:_files' \ ++ '(--env --env-branch)--env=[Specifies the environment to perform the operation using its handle]:env:' \ ++ '--env-branch=[Specifies the environment to perform the operation using its Git branch name]:env-branch:' \ ++ '--env-file=[Path to an environment file to override existing environment variables for...]:env-file:' \ ++ '(-f --force)'{-f,--force}'[Forces a deployment to proceed if there are uncommitted changes in its Git...]' \ ++ '--force-client-sourcemap[Client sourcemapping is avoided by default because it makes backend code...]' \ ++ '--json-output[Create a JSON file containing the deployment details in CI environments]' \ ++ '--lockfile-check[Checks that there is exactly one valid lockfile in the project]' \ ++ '--metadata-description=[Description of the changes in the deployment]:metadata-description:' \ ++ '--metadata-user=[User that initiated the deployment]:metadata-user:' \ ++ '--no-verify[Skip the routability verification step after deployment]' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '--preview[Deploys to the Preview environment]' \ ++ '(-s --shop)'{-s,--shop}'=[Shop URL]:shop:' \ ++ '(-t --token)'{-t,--token}'=[Oxygen deployment token]:token:' \ ++ '--worker-dir=[Directory containing the Oxygen worker entry point (`index.js` or...]:worker-dir:' ++} ++ ++_shopify__hydrogen__dev() { ++ _arguments -s -S \ ++ '--codegen[Automatically generates GraphQL types for your project’s Storefront API...]' \ ++ '--codegen-config-path=[Specifies a path to a codegen configuration file]:codegen-config-path:' \ ++ '--customer-account-push[Use tunneling for local development and push the tunneling domain to admin]' \ ++ '--debug[Enables inspector connections to the server with a debugger such as Visual...]' \ ++ '--disable-deps-optimizer[Disable adding dependencies to Vite'\''s `ssr.optimizeDeps.include`...]' \ ++ '--disable-version-check[Skip the version check when running `hydrogen dev`]' \ ++ '--disable-virtual-routes[Disable rendering fallback routes when a route file doesn'\''t exist]' \ ++ '--entry=[Entry file for the worker]:entry:_files' \ ++ '(--env --env-branch)--env=[Specifies the environment to perform the operation using its handle]:env:' \ ++ '--env-branch=[Specifies the environment to perform the operation using its Git branch name]:env-branch:' \ ++ '--env-file=[Path to an environment file to override existing environment variables]:env-file:' \ ++ '--host[Expose the server to the local network]' \ ++ '--inspector-port=[The port where the inspector is available]:inspector-port:' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '--port=[The port to run the server on]:port:' \ ++ '--verbose[Outputs more information about the command'\''s execution]' ++} ++ ++_shopify__hydrogen__env__list() { ++ _arguments -s -S \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' ++} ++ ++_shopify__hydrogen__env__pull() { ++ _arguments -s -S \ ++ '(--env --env-branch)--env=[Specifies the environment to perform the operation using its handle]:env:' \ ++ '--env-branch=[Specifies the environment to perform the operation using its Git branch name]:env-branch:' \ ++ '--env-file=[Path to an environment file to override existing environment variables]:env-file:' \ ++ '(-f --force)'{-f,--force}'[Overwrites the destination directory and files if they already exist]' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' ++} ++ ++_shopify__hydrogen__env__push() { ++ _arguments -s -S \ ++ '(--dry-run -f --force)--dry-run[Preview environment variable changes without pushing them]' \ ++ '--env=[Specifies the environment to perform the operation using its handle]:env:' \ ++ '--env-file=[Path to an environment file to override existing environment variables]:env-file:' \ ++ '(-f --force)'{-f,--force}'[Push environment variable changes without confirmation]' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' ++} ++ ++_shopify__hydrogen__env() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List the environments on your linked Hydrogen storefront' ++ 'pull:Populate your .env with variables from your Hydrogen storefront' ++ 'push:Push environment variables from the local .env file to your linked Hydrogen...' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'hydrogen env command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _shopify__hydrogen__env__list && ret=0 ;; ++ pull) _shopify__hydrogen__env__pull && ret=0 ;; ++ push) _shopify__hydrogen__env__push && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__hydrogen__generate__route() { ++ _arguments -s -S \ ++ '--adapter=[React Router adapter used in the route]:adapter:' \ ++ '(-f --force)'{-f,--force}'[Overwrites the destination directory and files if they already exist]' \ ++ '--locale-param=[The param name in Remix routes for the i18n locale, if any]:locale-param:' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '--typescript[Generate TypeScript files]' \ ++ '*:file:_files' ++} ++ ++_shopify__hydrogen__generate__routes() { ++ _arguments -s -S \ ++ '--adapter=[React Router adapter used in the route]:adapter:' \ ++ '(-f --force)'{-f,--force}'[Overwrites the destination directory and files if they already exist]' \ ++ '--locale-param=[The param name in Remix routes for the i18n locale, if any]:locale-param:' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '--typescript[Generate TypeScript files]' ++} ++ ++_shopify__hydrogen__generate() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'route:Generates a standard Shopify route' ++ 'routes:Generates all supported standard shopify routes' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'hydrogen generate command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ route) _shopify__hydrogen__generate__route && ret=0 ;; ++ routes) _shopify__hydrogen__generate__routes && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__hydrogen__init() { ++ _arguments -s -S \ ++ '(-f --force)'{-f,--force}'[Overwrites the destination directory and files if they already exist]' \ ++ '--git[Init Git and create initial commits]' \ ++ '--install-deps[Auto installs dependencies using the active package manager]' \ ++ '--language=[Sets the template language to use]:language:' \ ++ '--markets=[Sets the URL structure to support multiple markets]:markets:' \ ++ '--mock-shop[Use mock.shop as the data source for the storefront]' \ ++ '--path=[The path to the directory of the new Hydrogen storefront]:path:_files -/' \ ++ '--quickstart[Scaffolds a new Hydrogen project with a set of sensible defaults]' \ ++ '--shortcut[Creates a global h2 shortcut for Shopify CLI using shell aliases]' \ ++ '--styling=[Sets the styling strategy to use]:styling:' \ ++ '--template=[Scaffolds project based on an existing template or example from the...]:template:' ++} ++ ++_shopify__hydrogen__link() { ++ _arguments -s -S \ ++ '(--create-storefront --storefront)--create-storefront[Create a new Hydrogen storefront]' \ ++ '(-f --force)'{-f,--force}'[Overwrites the destination directory and files if they already exist]' \ ++ '(--name --storefront)--name=[The name to use when creating a new Hydrogen storefront]:name:' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '(-s --shop)'{-s,--shop}'=[Shop URL]:shop:' \ ++ '(--storefront --create-storefront --name)--storefront=[The name of a Hydrogen Storefront (e.g]:storefront:' ++} ++ ++_shopify__hydrogen__list() { ++ _arguments -s -S \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' ++} ++ ++_shopify__hydrogen__login() { ++ _arguments -s -S \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '(-s --shop)'{-s,--shop}'=[Shop URL]:shop:' ++} ++ ++_shopify__hydrogen__logout() { ++ _arguments -s -S \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' ++} ++ ++_shopify__hydrogen__preview() { ++ _arguments -s -S \ ++ '--build[Builds the app before starting the preview server]' \ ++ '--codegen[Automatically generates GraphQL types for your project’s Storefront API...]' \ ++ '--codegen-config-path=[Specifies a path to a codegen configuration file]:codegen-config-path:' \ ++ '--debug[Enables inspector connections to the server with a debugger such as Visual...]' \ ++ '--entry=[Entry file for the worker]:entry:_files' \ ++ '(--env --env-branch)--env=[Specifies the environment to perform the operation using its handle]:env:' \ ++ '--env-branch=[Specifies the environment to perform the operation using its Git branch name]:env-branch:' \ ++ '--env-file=[Path to an environment file to override existing environment variables]:env-file:' \ ++ '--inspector-port=[The port where the inspector is available]:inspector-port:' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '--port=[The port to run the server on]:port:' \ ++ '--verbose[Outputs more information about the command'\''s execution]' \ ++ '--watch[Watches for changes and rebuilds the project]' ++} ++ ++_shopify__hydrogen__setup__css() { ++ _arguments -s -S \ ++ '(-f --force)'{-f,--force}'[Overwrites the destination directory and files if they already exist]' \ ++ '--install-deps[Auto installs dependencies using the active package manager]' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '*:file:_files' ++} ++ ++_shopify__hydrogen__setup__markets() { ++ _arguments -s -S \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '*:file:_files' ++} ++ ++_shopify__hydrogen__setup__vite() { ++ _arguments -s -S \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' ++} ++ ++_shopify__hydrogen__setup() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'css:Setup CSS strategies for your project' ++ 'markets:Setup support for multiple markets in your project' ++ 'vite:EXPERIMENTAL\: Upgrades the project to use Vite' ++ ) ++ ++ _arguments -s -C \ ++ '(-f --force)'{-f,--force}'[Overwrites the destination directory and files if they already exist]' \ ++ '--install-deps[Auto installs dependencies using the active package manager]' \ ++ '--markets=[Sets the URL structure to support multiple markets]:markets:' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '--shortcut[Creates a global h2 shortcut for Shopify CLI using shell aliases]' \ ++ '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'hydrogen setup command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ css) _shopify__hydrogen__setup__css && ret=0 ;; ++ markets) _shopify__hydrogen__setup__markets && ret=0 ;; ++ vite) _shopify__hydrogen__setup__vite && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__hydrogen__shortcut() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify__hydrogen__unlink() { ++ _arguments -s -S \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' ++} ++ ++_shopify__hydrogen__upgrade() { ++ _arguments -s -S \ ++ '(-f --force)'{-f,--force}'[Ignore warnings and force the upgrade to the target version]' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '(-v --version)'{-v,--version}'=[A target hydrogen version to update to]:version:' ++} ++ ++_shopify__hydrogen() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'build:Builds a Hydrogen storefront for production' ++ 'check:Returns diagnostic information about a Hydrogen storefront' ++ 'codegen:Generate types for the Storefront API queries found in your project' ++ 'customer-account-push:Push project configuration to admin' ++ 'debug:Profile the storefront' ++ 'deploy:Builds and deploys a Hydrogen storefront to Oxygen' ++ 'dev:Runs Hydrogen storefront in an Oxygen worker for development' ++ 'env:Manage storefront environment variables' ++ 'generate:Generate standard Shopify routes' ++ 'init:Creates a new Hydrogen storefront' ++ 'link:Link a local project to one of your shop'\''s Hydrogen storefronts' ++ 'list:Returns a list of Hydrogen storefronts available on a given shop' ++ 'login:Login to your Shopify account' ++ 'logout:Logout of your local session' ++ 'preview:Runs a Hydrogen storefront in an Oxygen worker for production' ++ 'setup:Scaffold routes and core functionality' ++ 'shortcut:Creates a global `h2` shortcut for the Hydrogen CLI' ++ 'unlink:Unlink a local project from a Hydrogen storefront' ++ 'upgrade:Upgrade Remix and Hydrogen npm dependencies' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'hydrogen command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ build) _shopify__hydrogen__build && ret=0 ;; ++ check) _shopify__hydrogen__check && ret=0 ;; ++ codegen) _shopify__hydrogen__codegen && ret=0 ;; ++ customer-account-push) _shopify__hydrogen__customer_account_push && ret=0 ;; ++ debug) _shopify__hydrogen__debug && ret=0 ;; ++ deploy) _shopify__hydrogen__deploy && ret=0 ;; ++ dev) _shopify__hydrogen__dev && ret=0 ;; ++ env) _shopify__hydrogen__env && ret=0 ;; ++ generate) _shopify__hydrogen__generate && ret=0 ;; ++ init) _shopify__hydrogen__init && ret=0 ;; ++ link) _shopify__hydrogen__link && ret=0 ;; ++ list) _shopify__hydrogen__list && ret=0 ;; ++ login) _shopify__hydrogen__login && ret=0 ;; ++ logout) _shopify__hydrogen__logout && ret=0 ;; ++ preview) _shopify__hydrogen__preview && ret=0 ;; ++ setup) _shopify__hydrogen__setup && ret=0 ;; ++ shortcut) _shopify__hydrogen__shortcut && ret=0 ;; ++ unlink) _shopify__hydrogen__unlink && ret=0 ;; ++ upgrade) _shopify__hydrogen__upgrade && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__organization__list() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__organization() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List Shopify organizations you have access to' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'organization command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _shopify__organization__list && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__search() { ++ _arguments -s -S \ ++ '--no-color[Disable color output]' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '*:file:_files' ++} ++ ++_shopify__store__auth__list() { ++ _arguments -s -S \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__store__auth() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List stores authenticated directly with store auth' ++ ) ++ ++ _arguments -s -C \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--scopes=[Comma-separated Admin API scopes to request for the app]:scopes:' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store]:store:' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'store auth command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _shopify__store__auth__list && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__store__bulk__cancel() { ++ _arguments -s -S \ ++ '--id=[The bulk operation ID to cancel (numeric ID or full GID)]:id:' \ ++ '--no-color[Disable color output]' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__store__bulk__execute() { ++ _arguments -s -S \ ++ '--allow-mutations[Allow GraphQL mutations to run against the target store]' \ ++ '--no-color[Disable color output]' \ ++ '--output-file=[The file path where results should be written if --watch is specified]:output-file:' \ ++ '(-q --query)'{-q,--query}'=[The GraphQL query or mutation to run as a bulk operation]:query:' \ ++ '--query-file=[Path to a file containing the GraphQL query or mutation]:query-file:' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store]:store:' \ ++ '(--variable-file -v --variables)--variable-file=[Path to a file containing GraphQL variables in JSONL format (one JSON...]:variable-file:' \ ++ *''{-v,--variables}'=[The values for any GraphQL variables in your mutation, in JSON format]:variables:' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '--version=[The API version to use for the bulk operation]:version:' \ ++ '--watch[Wait for bulk operation results before exiting]' ++} ++ ++_shopify__store__bulk__status() { ++ _arguments -s -S \ ++ '--id=[The bulk operation ID (numeric ID or full GID)]:id:' \ ++ '--no-color[Disable color output]' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__store__bulk() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'cancel:Cancel a bulk operation on a store' ++ 'execute:Execute bulk operations on a store' ++ 'status:Check the status of bulk operations on a store' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'store bulk command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ cancel) _shopify__store__bulk__cancel && ret=0 ;; ++ execute) _shopify__store__bulk__execute && ret=0 ;; ++ status) _shopify__store__bulk__status && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__store__create__preview() { ++ _arguments -s -S \ ++ '--country=[Two-letter country code for the store, such as US, CA, or GB]:country:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--name=[The name of the store]:name:' \ ++ '--no-color[Disable color output]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__store__create() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'preview:Create a preview Shopify store' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'store create command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ preview) _shopify__store__create__preview && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__store__execute() { ++ _arguments -s -S \ ++ '--allow-mutations[Allow GraphQL mutations to run against the target store]' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--output-file=[The file name where results should be written, instead of STDOUT]:output-file:' \ ++ '(-q --query)'{-q,--query}'=[The GraphQL query or mutation, as a string]:query:' \ ++ '--query-file=[Path to a file containing the GraphQL query or mutation]:query-file:' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store]:store:' \ ++ '(--variable-file -v --variables)--variable-file=[Path to a file containing GraphQL variables in JSON format]:variable-file:' \ ++ '(-v --variables --variable-file)'{-v,--variables}'=[The values for any GraphQL variables in your query or mutation, in JSON...]:variables:' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '--version=[The API version to use for the query or mutation]:version:' ++} ++ ++_shopify__store__graphiql() { ++ _arguments -s -S \ ++ '--allow-mutations[Allow GraphQL mutations to run against the target store]' \ ++ '--no-color[Disable color output]' \ ++ '--port=[Local port for the GraphiQL server]:port:' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store]:store:' \ ++ '(-v --variables)'{-v,--variables}'=[The values for any GraphQL variables in your query or mutation, in JSON...]:variables:' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '--version=[The API version to use in GraphiQL]:version:' ++} ++ ++_shopify__store__info() { ++ _arguments -s -S \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__store__list() { ++ _arguments -s -S \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--organization-id=[The numeric organization ID]:organization-id:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__store__open() { ++ _arguments -s -S \ ++ '--no-color[Disable color output]' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__store() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'auth:Authenticate an app against a store for store commands' ++ 'bulk:Run bulk store operations' ++ 'create:Create a store' ++ 'execute:Execute GraphQL queries and mutations on a store' ++ 'graphiql:Open a local GraphiQL UI for a store' ++ 'info:Surface metadata about a Shopify store' ++ 'list:List stores in a Shopify organization' ++ 'open:Open your Shopify store in the default web browser' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'store command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ auth) _shopify__store__auth && ret=0 ;; ++ bulk) _shopify__store__bulk && ret=0 ;; ++ create) _shopify__store__create && ret=0 ;; ++ execute) _shopify__store__execute && ret=0 ;; ++ graphiql) _shopify__store__graphiql && ret=0 ;; ++ info) _shopify__store__info && ret=0 ;; ++ list) _shopify__store__list && ret=0 ;; ++ open) _shopify__store__open && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__theme__check() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(-a --auto-correct)'{-a,--auto-correct}'[Automatically fix offenses]' \ ++ '(-C --config)'{-C,--config}'=[Use the config provided, overriding .theme-check.yml if present]:config:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '--fail-level=[Minimum severity for exit with error code]:fail-level:(crash error suggestion style warning info)' \ ++ '--init[Generate a .theme-check.yml file]' \ ++ '--list[List enabled checks]' \ ++ '--no-color[Disable color output]' \ ++ '(-o --output)'{-o,--output}'=[The output format to use]:output:(text json)' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '--print[Output active config to STDOUT]' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '(-v --version)'{-v,--version}'[Print Theme Check version]' ++} ++ ++_shopify__theme__console() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--store-password=[The password for storefronts with password protection]:store-password:' \ ++ '--url=[The url to be used as context]:url:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__delete() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(-d --development)'{-d,--development}'[Delete your development theme]' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '(-f --force)'{-f,--force}'[Skip confirmation]' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-a --show-all)'{-a,--show-all}'[Include other development themes in the theme list]' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ *''{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__dev() { ++ _arguments -s -S \ ++ '(-a --allow-live)'{-a,--allow-live}'[Allow development on a live theme]' \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '--error-overlay=[Controls the visibility of the error overlay when an theme asset upload...]:error-overlay:(silent default)' \ ++ '--host=[Set which network interface the web server listens on]:host:_hosts' \ ++ *''{-x,--ignore}'=[Skip hot reloading any files that match the specified pattern]:ignore:_files' \ ++ '--listing=[The listing preset to use for multi-preset themes]:listing:' \ ++ '--live-reload=[The live reload mode switches the server behavior when a file is modified\:]:live-reload:(hot-reload full-page off)' \ ++ '--no-color[Disable color output]' \ ++ '(-n --nodelete)'{-n,--nodelete}'[Prevents files from being deleted in the remote theme when a file has been...]' \ ++ '--notify=[The file path or URL]:notify:_files' \ ++ *''{-o,--only}'=[Hot reload only files that match the specified pattern]:only:_files' \ ++ '--open[Automatically launch the theme preview in your default web browser]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '--port=[Local port to serve theme preview from]:port:' \ ++ '--reconciliation-strategy=[How to resolve JSON conflicts when --theme-editor-sync is enabled]:reconciliation-strategy:(keep-local keep-remote abort)' \ ++ '--standard-events-inspector[Inject the standard events inspector into storefront HTML]' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--store-password=[The password for storefronts with password protection]:store-password:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--theme-editor-sync[Synchronize Theme Editor updates in the local theme files]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__duplicate() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '(-f --force)'{-f,--force}'[Force the duplicate operation to run without prompts or confirmations]' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '(-n --name)'{-n,--name}'=[Name of the newly duplicated theme]:name:' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__info() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(-d --development)'{-d,--development}'[Retrieve info from your development theme]' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__init() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(-u --clone-url)'{-u,--clone-url}'=[The Git URL to clone from]:clone-url:' \ ++ '(-l --latest)'{-l,--latest}'[Downloads the latest release of the `clone-url`]' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '*:file:_files' ++} ++ ++_shopify__theme__language_server() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '--no-color[Disable color output]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__list() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '--id=[Only list theme with the given ID]:id:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--name=[Only list themes that contain the given name]:name:' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '--role=[Only list themes with the given role]:role:(live unpublished development)' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__metafields__pull() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__metafields() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'pull:Download metafields definitions from your shop into a local file' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'theme metafields command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ pull) _shopify__theme__metafields__pull && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__theme__open() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(-d --development)'{-d,--development}'[Open your development theme]' \ ++ '(-E --editor)'{-E,--editor}'[Open the theme editor for the specified theme in the browser]' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '(-l --live)'{-l,--live}'[Open your live (published) theme]' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__package() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__preview() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '--json[Output the preview URL and identifier as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--open[Automatically launch the theme preview in your default web browser]' \ ++ '--overrides=[Path to a JSON overrides file]:overrides:' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '--preview-id=[An existing preview identifier to update instead of creating a new preview]:preview-id:' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__profile() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--store-password=[The password for storefronts with password protection]:store-password:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--url=[The url to be used as context]:url:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__publish() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '(-f --force)'{-f,--force}'[Skip confirmation]' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__pull() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(-d --development)'{-d,--development}'[Pull theme files from your remote development theme]' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ *''{-x,--ignore}'=[Skip downloading the specified files (Multiple flags allowed)]:ignore:_files' \ ++ '(-l --live)'{-l,--live}'[Pull theme files from your remote live theme]' \ ++ '--no-color[Disable color output]' \ ++ '(-n --nodelete)'{-n,--nodelete}'[Prevent deleting local files that don'\''t exist remotely]' \ ++ *''{-o,--only}'=[Download only the specified files (Multiple flags allowed)]:only:_files' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__push() { ++ _arguments -s -S \ ++ '(-a --allow-live)'{-a,--allow-live}'[Allow push to a live theme]' \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(-d --development)'{-d,--development}'[Push theme files from your remote development theme]' \ ++ '(-c --development-context -t --theme)'{-c,--development-context}'=[Unique identifier for a development theme context (e.g., PR number, branch...]:development-context:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ *''{-x,--ignore}'=[Skip uploading the specified files (Multiple flags allowed)]:ignore:_files' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--listing=[The listing preset to use for multi-preset themes]:listing:' \ ++ '(-l --live)'{-l,--live}'[Push theme files from your remote live theme]' \ ++ '--no-color[Disable color output]' \ ++ '(-n --nodelete)'{-n,--nodelete}'[Prevent deleting remote files that don'\''t exist locally]' \ ++ *''{-o,--only}'=[Upload only the specified files (Multiple flags allowed)]:only:_files' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-p --publish)'{-p,--publish}'[Publish as the live theme after uploading]' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--strict[Require theme check to pass without errors before pushing]' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '(-u --unpublished)'{-u,--unpublished}'[Create a new unpublished theme and push to it]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__rename() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(-d --development)'{-d,--development}'[Rename your development theme]' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '(-l --live)'{-l,--live}'[Rename your remote live theme]' \ ++ '(-n --name)'{-n,--name}'=[The new name for the theme]:name:' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__share() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '--listing=[The listing preset to use for multi-preset themes]:listing:' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'check:Validate the theme' ++ 'console:Shopify Liquid REPL (read-eval-print loop) tool' ++ 'delete:Delete remote themes from the connected store' ++ 'dev:Uploads the current theme as a development theme to the connected store,...' ++ 'duplicate:Duplicates a theme from your theme library' ++ 'info:Displays information about your theme environment, including your current...' ++ 'init:Clones a Git repository to use as a starting point for building a new theme' ++ 'language-server:Start a Language Server Protocol server' ++ 'list:Lists the themes in your store, along with their IDs and statuses' ++ 'metafields:Theme metafield operations' ++ 'open:Opens the preview of your remote theme' ++ 'package:Package your theme into a .zip file, ready to upload to the Online Store' ++ 'preview:Applies JSON overrides to a theme and returns a preview URL' ++ 'profile:Profile the Liquid rendering of a theme page' ++ 'publish:Set a remote theme as the live theme' ++ 'pull:Download your remote theme files locally' ++ 'push:Uploads your local theme files to the connected store, overwriting the...' ++ 'rename:Renames an existing theme' ++ 'share:Creates a shareable, unpublished, and new theme on your theme library with...' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'theme command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ check) _shopify__theme__check && ret=0 ;; ++ console) _shopify__theme__console && ret=0 ;; ++ delete) _shopify__theme__delete && ret=0 ;; ++ dev) _shopify__theme__dev && ret=0 ;; ++ duplicate) _shopify__theme__duplicate && ret=0 ;; ++ info) _shopify__theme__info && ret=0 ;; ++ init) _shopify__theme__init && ret=0 ;; ++ language-server) _shopify__theme__language_server && ret=0 ;; ++ list) _shopify__theme__list && ret=0 ;; ++ metafields) _shopify__theme__metafields && ret=0 ;; ++ open) _shopify__theme__open && ret=0 ;; ++ package) _shopify__theme__package && ret=0 ;; ++ preview) _shopify__theme__preview && ret=0 ;; ++ profile) _shopify__theme__profile && ret=0 ;; ++ publish) _shopify__theme__publish && ret=0 ;; ++ pull) _shopify__theme__pull && ret=0 ;; ++ push) _shopify__theme__push && ret=0 ;; ++ rename) _shopify__theme__rename && ret=0 ;; ++ share) _shopify__theme__share && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__upgrade() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify__version() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'app:Build Shopify apps' ++ 'auth:Authentication operations' ++ 'commands:List all shopify commands' ++ 'config:CLI configuration options' ++ 'doc:Search the Shopify documentation' ++ 'help:Display help for Shopify CLI' ++ 'hydrogen:Build Hydrogen storefronts' ++ 'organization:Work with your organizations' ++ 'search:Search shopify.dev for the most relevant content matching a query' ++ 'store:Work with a store' ++ 'theme:Build Liquid themes' ++ 'upgrade:Upgrades Shopify CLI' ++ 'version:Shopify CLI version currently installed' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'shopify command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ app) _shopify__app && ret=0 ;; ++ auth) _shopify__auth && ret=0 ;; ++ commands) _shopify__commands && ret=0 ;; ++ config) _shopify__config && ret=0 ;; ++ doc) _shopify__doc && ret=0 ;; ++ help) _shopify__help && ret=0 ;; ++ hydrogen) _shopify__hydrogen && ret=0 ;; ++ organization) _shopify__organization && ret=0 ;; ++ search) _shopify__search && ret=0 ;; ++ store) _shopify__store && ret=0 ;; ++ theme) _shopify__theme && ret=0 ;; ++ upgrade) _shopify__upgrade && ret=0 ;; ++ version) _shopify__version && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify "$@" +diff --git a/plugins/shopify/shopify.plugin.zsh b/plugins/shopify/shopify.plugin.zsh +new file mode 100644 +index 00000000..e90fdae7 +--- /dev/null ++++ b/plugins/shopify/shopify.plugin.zsh +@@ -0,0 +1,203 @@ ++# Shopify CLI: completion, aliases and guard rails. ++# https://shopify.dev/docs/api/shopify-cli ++ ++if (( ! $+commands[shopify] )); then ++ return ++fi ++ ++# Prefer a project-local CLI: app and Hydrogen projects pin their own version. ++# The walk stops at $HOME so a stray ~/node_modules cannot hijack every project. ++# $commands avoids resolving back to the wrapper function below. ++function _shopify_bin() { ++ local dir="$PWD" ++ while [[ -n "$dir" && "$dir" != "/" && "$dir" != "$HOME" ]]; do ++ if [[ -x "$dir/node_modules/.bin/shopify" ]]; then ++ print -r -- "$dir/node_modules/.bin/shopify" ++ return 0 ++ fi ++ dir="${dir:h}" ++ done ++ print -r -- "$commands[shopify]" ++} ++ ++# Print the project type in $PWD: hydrogen, app or theme. ++# Hydrogen is tested first because those projects usually carry a ++# shopify.app.toml too. shopify.theme.toml is not a theme marker: it only ++# exists once environments are configured. ++function _shopify_project_type() { ++ local dir="$PWD" ++ local -a app_config ++ ++ while [[ -n "$dir" && "$dir" != "/" && "$dir" != "$HOME" ]]; do ++ if [[ -x "$dir/node_modules/.bin/h2" ]] || ++ [[ -r "$dir/package.json" && "$(<"$dir/package.json")" == *'"@shopify/hydrogen"'* ]]; then ++ return 0 ++ fi ++ ++ app_config=("$dir"/shopify.app*.toml(N)) ++ if (( $#app_config )); then ++ print -r -- app ++ return 0 ++ fi ++ ++ if [[ -f "$dir/config/settings_schema.json" && -f "$dir/layout/theme.liquid" ]]; then ++ print -r -- theme ++ return 0 ++ fi ++ ++ dir="${dir:h}" ++ done ++ ++ return 1 ++} ++ ++# Does this invocation need confirming? Sets REPLY to the reason. ++function _shopify_is_destructive() { ++ zstyle -T ':omz:plugins:shopify' confirm-destructive || return 1 ++ ++ # Nobody to answer: CI and pipelines are unaffected. ++ [[ -t 0 ]] || return 1 ++ ++ local topic="$1" subcommand="$2" arg ++ local -a long ++ local short="" ++ ++ # Short flags can be bundled, so collect them as characters: -al counts as l. ++ for arg in "${@[3,-1]}"; do ++ [[ "$arg" == "--" ]] && break ++ case "$arg" in ++ --*) long+=("${arg%%=*}") ;; ++ -?*) short+="${${arg%%=*}#-}" ;; ++ esac ++ done ++ ++ # An explicit force flag states the intent already. ++ if (( long[(I)--force] )) || [[ "$short" == *f* ]]; then ++ return 1 ++ fi ++ ++ case "$topic $subcommand" in ++ "theme push") ++ if (( long[(I)--live] || long[(I)--publish] )) || [[ "$short" == *[lp]* ]]; then ++ REPLY="this overwrites or publishes the live theme on the storefront." ++ return 0 ++ fi ++ ;; ++ "theme delete") ++ REPLY="deleting a theme cannot be undone." ++ return 0 ++ ;; ++ "app deploy") ++ if (( long[(I)--allow-deletes] )); then ++ REPLY="this can permanently remove app extensions." ++ return 0 ++ fi ++ ;; ++ esac ++ ++ return 1 ++} ++ ++# Adds a confirmation prompt before irreversible operations. Everything else ++# passes straight through, so `theme dev` stays interactive and pipes stay clean. ++function shopify() { ++ local REPLY ++ if _shopify_is_destructive "$@"; then ++ print -u2 -- "shopify: $REPLY" ++ if ! read -q "?Continue? [y/N] "; then ++ print -u2 -- "" ++ return 130 ++ fi ++ print -u2 -- "" ++ fi ++ ++ "$(_shopify_bin)" "$@" ++} ++ ++# Print the commands worth running in the current directory. ++function shopify_here() { ++ local project_type ++ project_type="$(_shopify_project_type)" ++ ++ case "$project_type" in ++ theme) ++ print -- "Shopify theme project." ++ print -- " shopify theme dev Preview locally with live reload" ++ print -- " shopify theme check Lint the theme" ++ print -- " shopify theme list List the themes on the store" ++ print -- " shopify theme pull Download a remote theme into this folder" ++ print -- " shopify theme push Upload this folder to a remote theme" ++ ;; ++ app) ++ print -- "Shopify app project." ++ print -- " shopify app dev Run the app against a development store" ++ print -- " shopify app info Show how the app is configured" ++ print -- " shopify app deploy Deploy the app and its extensions" ++ print -- " shopify app logs Stream app logs" ++ ;; ++ hydrogen) ++ print -- "Hydrogen storefront." ++ print -- " shopify hydrogen dev Run the storefront locally" ++ print -- " shopify hydrogen build Build for production" ++ print -- " shopify hydrogen deploy Deploy to Oxygen" ++ print -- " shopify hydrogen link Link this project to a storefront" ++ ;; ++ *) ++ print -- "No Shopify project found here." ++ print -- " shopify theme init Start a new theme" ++ print -- " shopify app init Start a new app" ++ print -- " shopify hydrogen init Start a new Hydrogen storefront" ++ ;; ++ esac ++} ++ ++# Run the dev server for whichever kind of project this is. ++function shopd() { ++ local project_type ++ if ! project_type="$(_shopify_project_type)"; then ++ print -u2 -- "shopd: not inside a Shopify theme, app or Hydrogen project." ++ return 1 ++ fi ++ shopify "$project_type" dev "$@" ++} ++ ++# Show what the current project is connected to. ++function shopi() { ++ local project_type ++ if ! project_type="$(_shopify_project_type)"; then ++ print -u2 -- "shopi: not inside a Shopify theme, app or Hydrogen project." ++ return 1 ++ fi ++ case "$project_type" in ++ hydrogen) shopify hydrogen list "$@" ;; ++ *) shopify "$project_type" info "$@" ;; ++ esac ++} ++ ++# Complete the helpers like the commands they stand in for. ++if (( $+functions[compdef] )); then ++ _shopd() { ++ local project_type ++ project_type="$(_shopify_project_type)" || return 1 ++ words=(shopify "$project_type" dev ${words[2,-1]}) ++ (( CURRENT += 2 )) ++ _shopify ++ } ++ ++ _shopi() { ++ local project_type ++ project_type="$(_shopify_project_type)" || return 1 ++ if [[ "$project_type" == hydrogen ]]; then ++ words=(shopify hydrogen list ${words[2,-1]}) ++ else ++ words=(shopify "$project_type" info ${words[2,-1]}) ++ fi ++ (( CURRENT += 2 )) ++ _shopify ++ } ++ ++ compdef _shopd shopd ++ compdef _shopi shopi ++fi ++ ++alias shop='shopify' diff --git a/tasks/ohmyzsh__ohmyzsh-14037/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14037/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14037/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14037/task.toml b/tasks/ohmyzsh__ohmyzsh-14037/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5f14e74c2975d987b32a88c26f1b255e3b0e00aa --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14037/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14037" +description = "feat(shopify): add plugin for Shopify CLI" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "3f84a2ae4ab63343890ff90efca6d18b7292dd0f" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14037" +source_access = "auto" +built_at = "2026-11-16T16:09:56.954023+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d98aed5411eab94645474ff17f867c4d72572bbcd837d9aa28c8000002dc1ab2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-14T19:41:29Z" +diff_format = "unified" +context_files = [ + "plugins/shopify/README.md", + "plugins/shopify/_shopify", + "plugins/shopify/shopify.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 2360 +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.970834+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:88349a534cc814f6bf642113d0a6f340c33ab9ffea441cc1aa2aed2313d50b0e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14037/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14037/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14037/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14037/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14037/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c37ec78c6043484cda6232a6d719129b3c092bab --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14037/tests/instruction.md @@ -0,0 +1,55 @@ +# Issue + +**Title:** feat(shopify): add plugin for Shopify CLI + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Screenshot + +image + + +## Changes: + +While working on the Shopify theme for [CommitGoods.com](https://commitgoods.com/) I kept wishing I had the +same shortcuts I have for everything else in my shell, so I put them in a plugin. + +It adds completion for the Shopify CLI, one alias (`shop`), and a few helpers +that pick the right command for whichever kind of project you are in — `shopd` +runs `theme dev`, `app dev` or `hydrogen dev` depending on the directory. The +CLI ships no completion generator of its own, so `_shopify` is generated from +`shopify commands --json` and checked in, the way `cdk` and `terraform` already +do. It targets Shopify CLI 4.x. + +It also asks for confirmation before three irreversible commands: +`theme push --live`, `theme delete`, and `app deploy --allow-deletes`. That is +skipped when `--force` is set or stdin is not a terminal, so scripts and CI are +unaffected, and it can be turned off with a zstyle. + +## Other comments: + +Only one alias, `shop`, on the guide's preference for one generic alias over +many specific ones. It collides with nothing in the tree and is not a real +command. + +`zsh -n` passes on both files. I tested the completion and the confirmation +prompt by hand across theme, app and Hydrogen projects. + +Written with Claude Code; I verified the CLI surface and tested it myself. +Testers welcome, especially on apps and Hydrogen — my own use here is themes. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3f84a2ae4ab6`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14037/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14037/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..cc9b1aea08e6acf7a054704f3c7d03982aedc737 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14037/tests/oracle.patch @@ -0,0 +1,2378 @@ +diff --git a/plugins/shopify/README.md b/plugins/shopify/README.md +new file mode 100644 +index 00000000..e07faa8f +--- /dev/null ++++ b/plugins/shopify/README.md +@@ -0,0 +1,112 @@ ++# Shopify CLI plugin ++ ++This plugin adds aliases, helper functions and completion for the ++[Shopify CLI](https://shopify.dev/docs/api/shopify-cli). ++ ++To use it, add `shopify` to the plugins array in your zshrc file: ++ ++```zsh ++plugins=(... shopify) ++``` ++ ++## Requirements ++ ++[Shopify CLI](https://shopify.dev/docs/api/shopify-cli) 4.0 or newer, installed ++and on your `PATH`. The plugin does nothing if it is not: ++ ++```zsh ++npm install -g @shopify/cli ++# or ++brew tap shopify/shopify && brew install shopify-cli ++``` ++ ++## Aliases ++ ++| Alias | Command | Description | ++| :----- | :-------- | :--------------------- | ++| `shop` | `shopify` | The Shopify CLI itself | ++ ++## Functions ++ ++| Function | Description | ++| :------------- | :--------------------------------------------------------------------------------- | ++| `shopd` | Runs `theme dev`, `app dev` or `hydrogen dev`, whichever fits the current project | ++| `shopi` | Shows what the current project is connected to | ++| `shopify_here` | Prints the kind of Shopify project you are in and the commands worth running in it | ++| `shopify` | Wraps the CLI to confirm before irreversible commands. See Settings | ++ ++`shopd` and `shopi` work out which topic applies by looking at the project you ++are standing in, so you do not have to remember whether this directory is a ++theme, an app or a Hydrogen storefront. They complete like the command they ++stand in for, so in a theme `shopd --` offers the flags of ++`shopify theme dev`. ++ ++## Completion ++ ++Every command completes with a description of what it does, at every level, and ++so do their flags, short forms and allowed values. `--environment` completes ++from the `[environments.*]` sections of your local `shopify.theme.toml` or ++`shopify.app.toml`. ++ ++The Shopify CLI ships no completion generator of its own, so `_shopify` is ++generated from `shopify commands --json` and kept in this repository. It targets ++Shopify CLI 4.x. ++ ++## Settings ++ ++Set these with `zstyle` in your zshrc, before Oh My Zsh is sourced. ++ ++### Confirming destructive commands ++ ++```zsh ++zstyle ':omz:plugins:shopify' confirm-destructive no ++``` ++ ++By default the plugin asks for confirmation before three irreversible ++operations: ++ ++- `shopify theme push` with `--live`/`-l` or `--publish`/`-p`, which overwrites ++ or publishes the live storefront ++- `shopify theme delete`, which the CLI's own help describes as impossible to ++ undo ++- `shopify app deploy --allow-deletes`, which can permanently remove extensions ++ ++Nothing else is intercepted, and the prompt is skipped when the command already ++carries `--force`/`-f` or when stdin is not a terminal, so scripts, pipelines ++and CI are unaffected. Set the style to `no` to turn the prompt off entirely. ++ ++### Completing theme IDs ++ ++```zsh ++zstyle ':omz:plugins:shopify' dynamic-theme-completion yes ++``` ++ ++Off by default. When enabled, `--theme` is completed from ++`shopify theme list --json`, showing each theme's name and role next to its ID ++instead of making you copy IDs by hand. It is opt-in because it runs the CLI and ++makes a network call when you press Tab, and because it needs you to ++be authenticated. Results are cached for five minutes. ++ ++### Disabling the aliases ++ ++This works for every Oh My Zsh plugin: ++ ++```zsh ++zstyle ':omz:plugins:shopify' aliases no ++``` ++ ++## Caveats ++ ++- `shopify` is a shell function here. Run `command shopify` to reach the binary ++ directly. ++- When a project has its own copy of the CLI in `node_modules/.bin/shopify`, ++ that one is used in preference to the global install. App and Hydrogen ++ projects normally pin the CLI in `package.json`, and running a different ++ global version against them is a common source of confusing errors. ++- `--password` and `--store-password` are unrelated, and you often need both. ++ `--password` is the CLI's own authentication token, from the Theme Access app ++ or the Admin API. `--store-password` is the password for a ++ password-protected storefront. ++- `shopify theme push` deletes remote files that are missing locally, and ++ `shopify theme pull` deletes local files that are missing remotely, unless you ++ pass `--nodelete`/`-n`. The plugin does not prompt for these. +diff --git a/plugins/shopify/_shopify b/plugins/shopify/_shopify +new file mode 100644 +index 00000000..2f6d6ca2 +--- /dev/null ++++ b/plugins/shopify/_shopify +@@ -0,0 +1,2045 @@ ++#compdef shopify ++ ++# Completion for the Shopify CLI. https://shopify.dev/docs/api/shopify-cli ++# ++# Targets Shopify CLI 4.x. The CLI has no `completion`/`autocomplete` command, ++# so this is generated from `shopify commands --json` and kept here. Nothing ++# runs the CLI at completion time unless theme completion is enabled below. ++ ++# Environment names from the project's TOML config. Offline, always enabled. ++_shopify_environments() { ++ setopt localoptions extendedglob ++ local -a envs ++ local file line ++ # (#b) backreferences set $match, which would otherwise be left global. ++ local MATCH MBEGIN MEND ++ local -a match mbegin mend ++ for file in shopify.theme.toml shopify.app.toml; do ++ [[ -r "$file" ]] || continue ++ for line in ${(f)"$(< $file)"}; do ++ [[ $line == (#b)[[:space:]]#\[environments\.([^]]##)\]* ]] && envs+=("$match[1]") ++ done ++ done ++ (( $#envs )) || return 1 ++ _describe -t environments 'environment' envs ++} ++ ++# Theme IDs, described by name and role. Off by default: needs auth and makes a ++# network call on TAB. Enable with: ++# zstyle ':omz:plugins:shopify' dynamic-theme-completion yes ++_shopify_themes() { ++ zstyle -t ':omz:plugins:shopify' dynamic-theme-completion || return 1 ++ ++ local key="${${PWD:A}//\//-}" ++ local cache_file="$ZSH_CACHE_DIR/shopify-themes${key: -100}" ++ local -a themes fresh ++ local json split entry id name role ++ # $match and friends are set by =~ and would otherwise be left global. ++ local MATCH MBEGIN MEND ++ local -a match mbegin mend ++ local nl=$'\n' ++ ++ # Reuse the cached list for five minutes. ++ fresh=(${cache_file}(Nms-300)) ++ if (( $#fresh )); then ++ themes=("${(@f)$(< "$cache_file")}") ++ else ++ json="$(shopify theme list --json 2>/dev/null)" || return 1 ++ split="${json//\{/$nl}" ++ for entry in ${(f)split}; do ++ id="" name="" role="" ++ [[ $entry =~ '"id":[[:space:]]*([0-9]+)' ]] && id=$match[1] ++ [[ $entry =~ '"name":[[:space:]]*"([^"]*)"' ]] && name=$match[1] ++ [[ $entry =~ '"role":[[:space:]]*"([^"]*)"' ]] && role=$match[1] ++ [[ -n $id ]] || continue ++ themes+=("${id}:${name}${role:+ (${role})}") ++ done ++ (( $#themes )) || return 1 ++ print -rl -- $themes > "$cache_file" ++ fi ++ ++ _describe -t shopify-themes 'theme' themes ++} ++ ++_shopify__app__build() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--skip-dependencies-installation[Skips the installation of dependencies]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__bulk__cancel() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--id=[The bulk operation ID to cancel (numeric ID or full GID)]:id:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '(-s --store)'{-s,--store}'=[The store domain]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__bulk__execute() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--output-file=[The file path where results should be written if --watch is specified]:output-file:' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(-q --query)'{-q,--query}'=[The GraphQL query or mutation to run as a bulk operation]:query:' \ ++ '--query-file=[Path to a file containing the GraphQL query or mutation]:query-file:' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '(-s --store)'{-s,--store}'=[The store domain]:store:' \ ++ '(--variable-file -v --variables)--variable-file=[Path to a file containing GraphQL variables in JSONL format (one JSON...]:variable-file:' \ ++ *''{-v,--variables}'=[The values for any GraphQL variables in your mutation, in JSON format]:variables:' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '--version=[The API version to use for the bulk operation]:version:' \ ++ '--watch[Wait for bulk operation results before exiting]' ++} ++ ++_shopify__app__bulk__status() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--id=[The bulk operation ID (numeric ID or full GID)]:id:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '(-s --store)'{-s,--store}'=[The store domain]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__bulk() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'cancel:Cancel a bulk operation' ++ 'execute:Execute bulk operations' ++ 'status:Check the status of bulk operations' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app bulk command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ cancel) _shopify__app__bulk__cancel && ret=0 ;; ++ execute) _shopify__app__bulk__execute && ret=0 ;; ++ status) _shopify__app__bulk__status && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__app__config__link() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '(--file-name -c --config)--file-name=[The name of the app configuration file to create or overwrite]:file-name:' \ ++ '--force[Overwrite an existing configuration file without prompting]' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__config__pull() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__config__use() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '--client-id=[The Client ID of your app]:client-id:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '*:file:_files' ++} ++ ++_shopify__app__config__validate() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__config() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'link:Fetch your app configuration from the Developer Dashboard' ++ 'pull:Refresh an already-linked app configuration without prompts' ++ 'use:Activate an app configuration' ++ 'validate:Validate your app configuration and extensions' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app config command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ link) _shopify__app__config__link && ret=0 ;; ++ pull) _shopify__app__config__pull && ret=0 ;; ++ use) _shopify__app__config__use && ret=0 ;; ++ validate) _shopify__app__config__validate && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__app__deploy() { ++ _arguments -s -S \ ++ '--allow-deletes[Allows removing extensions and configuration without requiring user...]' \ ++ '--allow-updates[Allows adding and updating extensions and configuration without requiring...]' \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--message=[Optional message that will be associated with this version]:message:' \ ++ '--no-build[Use with caution\: Skips building any elements of the app that require...]' \ ++ '--no-color[Disable color output]' \ ++ '(--no-release --allow-updates --allow-deletes)--no-release[Creates a version but doesn'\''t release it - it'\''s not made available to...]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--source-control-url=[URL associated with the new app version]:source-control-url:' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '--version=[Optional version tag that will be associated with this app version]:version:' ++} ++ ++_shopify__app__dev__clean() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__dev() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'clean:Cleans up the dev preview from the selected store' ++ ) ++ ++ _arguments -s -C \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '--checkout-cart-url=[Resource URL for checkout UI extension]:checkout-cart-url:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--install-mkcert[Install and use mkcert to generate localhost certificates when...]' \ ++ '--localhost-port=[Port to use for localhost]:localhost-port:' \ ++ '--no-color[Disable color output]' \ ++ '--no-update[Uses the app URL from the toml file instead an autogenerated URL for dev]' \ ++ '--notify=[The file path or URL]:notify:_files' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--skip-dependencies-installation[Skips the installation of dependencies]' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--store-password=[The password for storefronts with password protection]:store-password:' \ ++ '--subscription-product-url=[Resource URL for subscription UI extension]:subscription-product-url:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the theme app extension host theme]:theme:' \ ++ '--theme-app-extension-port=[Local port of the theme app extension development server]:theme-app-extension-port:' \ ++ '--tunnel-url=[Use a custom tunnel, it must be running before executing dev]:tunnel-url:' \ ++ '(--use-localhost --tunnel-url)--use-localhost[Service entry point will listen to localhost]' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app dev command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ clean) _shopify__app__dev__clean && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__app__env__pull() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--env-file=[Specify an environment file to update if the update flag is set]:env-file:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__env__show() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__env() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'pull:Pull app and extensions environment variables' ++ 'show:Display app and extensions environment variables' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app env command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ pull) _shopify__app__env__pull && ret=0 ;; ++ show) _shopify__app__env__show && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__app__execute() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--output-file=[The file name where results should be written, instead of STDOUT]:output-file:' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(-q --query)'{-q,--query}'=[The GraphQL query or mutation, as a string]:query:' \ ++ '--query-file=[Path to a file containing the GraphQL query or mutation]:query-file:' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store to execute against]:store:' \ ++ '(--variable-file -v --variables)--variable-file=[Path to a file containing GraphQL variables in JSON format]:variable-file:' \ ++ '(-v --variables --variable-file)'{-v,--variables}'=[The values for any GraphQL variables in your query or mutation, in JSON...]:variables:' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '--version=[The API version to use for the query or mutation]:version:' ++} ++ ++_shopify__app__function__build() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your function directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__function__info() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your function directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__function__replay() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '(-l --log)'{-l,--log}'=[Specifies a log identifier to replay instead of selecting from a list]:log:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your function directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '(-w --watch)'{-w,--watch}'[Re-run the function when the source code changes]' ++} ++ ++_shopify__app__function__run() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '(-e --export)'{-e,--export}'=[Name of the WebAssembly export to invoke]:export:' \ ++ '(-i --input)'{-i,--input}'=[The input JSON to pass to the function]:input:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your function directory]:path:_files -/' \ ++ '--profile[Generate a WebAssembly performance profile for the function run]' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__function__schema() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your function directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--stdout[Output the schema to stdout instead of writing to a file]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__function__typegen() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your function directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__function() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'build:Compile a function to wasm' ++ 'info:Print basic information about your function' ++ 'replay:Replays a function run from an app log' ++ 'run:Run a function locally for testing' ++ 'schema:Fetch the latest GraphQL schema for a function' ++ 'typegen:Generate GraphQL types for a function' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app function command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ build) _shopify__app__function__build && ret=0 ;; ++ info) _shopify__app__function__info && ret=0 ;; ++ replay) _shopify__app__function__replay && ret=0 ;; ++ run) _shopify__app__function__run && ret=0 ;; ++ schema) _shopify__app__function__schema && ret=0 ;; ++ typegen) _shopify__app__function__typegen && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__app__generate__extension() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--flavor=[Choose a starting template for your extension, where applicable]:flavor:(vanilla-js react typescript typescript-react wasm rust)' \ ++ '(-n --name)'{-n,--name}'=[name of your Extension]:name:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '(-t --template)'{-t,--template}'=[Extension template]:template:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__generate() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'extension:Generate a new app Extension' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app generate command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ extension) _shopify__app__generate__extension && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__app__graphiql() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '--port=[Local port for the GraphiQL server]:port:' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store to open GraphiQL against]:store:' \ ++ '(-v --variables)'{-v,--variables}'=[The values for any GraphQL variables in your query or mutation, in JSON...]:variables:' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '--version=[The API version to use in GraphiQL]:version:' ++} ++ ++_shopify__app__import_custom_data_definitions() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--include-existing[Include existing declared definitions in the output]' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__import_extensions() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__info() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '--web-env[Outputs environment variables necessary for running and deploying web/]' ++} ++ ++_shopify__app__init() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '--client-id=[The Client ID of your app]:client-id:' \ ++ '--flavor=[Which flavor of the given template to use]:flavor:' \ ++ '(-n --name)'{-n,--name}'=[The name for the new app]:name:' \ ++ '--no-color[Disable color output]' \ ++ '(--organization-id --client-id)--organization-id=[The organization ID]:organization-id:' \ ++ '(-d --package-manager)'{-d,--package-manager}'=[]:package-manager:(npm yarn pnpm bun)' \ ++ '(-p --path)'{-p,--path}'=[]:path:_files -/' \ ++ '--template=[The app template]:template:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__logs__sources() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__logs() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'sources:Print out a list of sources that may be used with the logs command' ++ ) ++ ++ _arguments -s -C \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ *'--source=[Filters output to the specified log source]:source:' \ ++ '--status=[Filters output to the specified status (success or failure)]:status:(success failure)' \ ++ *''{-s,--store}'=[Store URL]:store:' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app logs command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ sources) _shopify__app__logs__sources && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__app__release() { ++ _arguments -s -S \ ++ '--allow-deletes[Allows removing extensions and configuration without requiring user...]' \ ++ '--allow-updates[Allows adding and updating extensions and configuration without requiring...]' \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '--version=[The name of the app version to release]:version:' ++} ++ ++_shopify__app__versions__list() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__app__versions() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List deployed versions of your app' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app versions command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _shopify__app__versions__list && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__app__webhook__trigger() { ++ _arguments -s -S \ ++ '--address=[The URL where the webhook payload should be sent]:address:' \ ++ '--api-version=[The API Version of the webhook topic]:api-version:' \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(--client-id -c --config)--client-id=[The Client ID of your app]:client-id:' \ ++ '--client-secret=[Your app'\''s client secret]:client-secret:' \ ++ '(-c --config)'{-c,--config}'=[The name of the app configuration]:config:' \ ++ '--delivery-method=[Method chosen to deliver the topic payload]:delivery-method:(http google-pub-sub event-bridge)' \ ++ '--help[This help]' \ ++ '--path=[The path to your app directory]:path:_files -/' \ ++ '(--reset -c --config)--reset[Reset all your settings]' \ ++ '--topic=[The requested webhook topic]:topic:' ++} ++ ++_shopify__app__webhook() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'trigger:Trigger delivery of a sample webhook topic payload to a designated address' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app webhook command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ trigger) _shopify__app__webhook__trigger && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__app() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'build:Build the app, including extensions' ++ 'bulk:Run bulk operations' ++ 'config:Manage app configuration files' ++ 'deploy:Deploy your Shopify app' ++ 'dev:Run the app' ++ 'env:Manage app environment variables' ++ 'execute:Execute GraphQL queries and mutations' ++ 'function:Work with Shopify Functions' ++ 'generate:Scaffold app extensions' ++ 'graphiql:Open a local GraphiQL UI for your app and store' ++ 'import-custom-data-definitions:Import metafield and metaobject definitions' ++ 'import-extensions:Import dashboard-managed extensions into your app' ++ 'info:Print basic information about your app and extensions' ++ 'init:Create a new app project' ++ 'logs:Stream detailed logs for your Shopify app' ++ 'release:Release an app version' ++ 'versions:Work with deployed app versions' ++ 'webhook:Trigger sample webhooks' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'app command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ build) _shopify__app__build && ret=0 ;; ++ bulk) _shopify__app__bulk && ret=0 ;; ++ config) _shopify__app__config && ret=0 ;; ++ deploy) _shopify__app__deploy && ret=0 ;; ++ dev) _shopify__app__dev && ret=0 ;; ++ env) _shopify__app__env && ret=0 ;; ++ execute) _shopify__app__execute && ret=0 ;; ++ function) _shopify__app__function && ret=0 ;; ++ generate) _shopify__app__generate && ret=0 ;; ++ graphiql) _shopify__app__graphiql && ret=0 ;; ++ import-custom-data-definitions) _shopify__app__import_custom_data_definitions && ret=0 ;; ++ import-extensions) _shopify__app__import_extensions && ret=0 ;; ++ info) _shopify__app__info && ret=0 ;; ++ init) _shopify__app__init && ret=0 ;; ++ logs) _shopify__app__logs && ret=0 ;; ++ release) _shopify__app__release && ret=0 ;; ++ versions) _shopify__app__versions && ret=0 ;; ++ webhook) _shopify__app__webhook && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__auth__login() { ++ _arguments -s -S \ ++ '--alias=[Alias of an existing session you want to use]:alias:' ++} ++ ++_shopify__auth__logout() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify__auth() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'login:Logs you in to your Shopify account' ++ 'logout:Logs you out of the Shopify account or Partner account and store' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'auth command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ login) _shopify__auth__login && ret=0 ;; ++ logout) _shopify__auth__logout && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__commands() { ++ _arguments -s -S \ ++ *''{-c,--columns}'=[Only show provided columns (comma-separated)]:columns:(id plugin summary type)' \ ++ '--deprecated[Show deprecated commands]' \ ++ '(-x --extended --tree)'{-x,--extended}'[Show extra columns]' \ ++ '--hidden[Show hidden commands]' \ ++ '--json[Format output as json]' \ ++ '(--no-truncate --tree)--no-truncate[Do not truncate output]' \ ++ '(--sort --tree)--sort=[Property to sort by]:sort:(id plugin summary type)' \ ++ '--tree[Show tree of commands]' ++} ++ ++_shopify__config__autocorrect__off() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify__config__autocorrect__on() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify__config__autocorrect__status() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify__config__autocorrect() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'off:Disable autocorrect' ++ 'on:Enable autocorrect' ++ 'status:Check whether autocorrect is enabled or disabled' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'config autocorrect command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ off) _shopify__config__autocorrect__off && ret=0 ;; ++ on) _shopify__config__autocorrect__on && ret=0 ;; ++ status) _shopify__config__autocorrect__status && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__config__autoupgrade__off() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify__config__autoupgrade__on() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify__config__autoupgrade__status() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify__config__autoupgrade() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'off:Disable automatic upgrades for Shopify CLI' ++ 'on:Enable automatic upgrades for Shopify CLI' ++ 'status:Check whether auto-upgrade is enabled, disabled, or not yet configured' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'config autoupgrade command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ off) _shopify__config__autoupgrade__off && ret=0 ;; ++ on) _shopify__config__autoupgrade__on && ret=0 ;; ++ status) _shopify__config__autoupgrade__status && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__config() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'autocorrect:Enable or disable command autocorrect' ++ 'autoupgrade:Enable or disable automatic upgrades' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'config command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ autocorrect) _shopify__config__autocorrect && ret=0 ;; ++ autoupgrade) _shopify__config__autoupgrade && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__doc__fetch() { ++ _arguments -s -S \ ++ '--no-color[Disable color output]' \ ++ '--output=[Write the document to this file path instead of printing it to stdout]:output:' \ ++ '--url=[The shopify.dev URL to fetch]:url:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__doc__search() { ++ _arguments -s -S \ ++ '--api-name=[Limit results to a specific API (for example\: admin, storefront, hydrogen,...]:api-name:' \ ++ '--api-version=[Limit results to a specific API version (for example\: 2025-10, latest,...]:api-version:' \ ++ '--no-color[Disable color output]' \ ++ '--query=[The search query]:query:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__doc() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'fetch:Download a complete document from shopify.dev' ++ 'search:Query the shopify.dev vector store and print the most relevant...' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'doc command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ fetch) _shopify__doc__fetch && ret=0 ;; ++ search) _shopify__doc__search && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__help() { ++ _arguments -s -S \ ++ '(-n --nested-commands)'{-n,--nested-commands}'[Include all nested commands in the output]' \ ++ '*:file:_files' ++} ++ ++_shopify__hydrogen__build() { ++ _arguments -s -S \ ++ '--bundle-stats[Show a bundle size summary after building]' \ ++ '--codegen[Automatically generates GraphQL types for your project’s Storefront API...]' \ ++ '--codegen-config-path=[Specifies a path to a codegen configuration file]:codegen-config-path:' \ ++ '--disable-route-warning[Disables any warnings about missing standard routes]' \ ++ '--entry=[Entry file for the worker]:entry:_files' \ ++ '--force-client-sourcemap[Client sourcemapping is avoided by default because it makes backend code...]' \ ++ '--lockfile-check[Checks that there is exactly one valid lockfile in the project]' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '--sourcemap[Controls whether server sourcemaps are generated]' \ ++ '--watch[Watches for changes and rebuilds the project writing output to disk]' ++} ++ ++_shopify__hydrogen__check() { ++ _arguments -s -S \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '*:file:_files' ++} ++ ++_shopify__hydrogen__codegen() { ++ _arguments -s -S \ ++ '--codegen-config-path=[Specify a path to a codegen configuration file]:codegen-config-path:' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '--watch[Watch the project for changes to update types on file save]' ++} ++ ++_shopify__hydrogen__customer_account_push() { ++ _arguments -s -S \ ++ '--dev-origin=[The development domain of your application]:dev-origin:' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '--relative-logout-uri=[The relative url of allowed url that will be redirected to post-logout for...]:relative-logout-uri:' \ ++ '--relative-redirect-uri=[The relative url of allowed callback url for Customer Account API OAuth flow]:relative-redirect-uri:' \ ++ '--storefront-id=[The id of the storefront the configuration should be pushed to]:storefront-id:' ++} ++ ++_shopify__hydrogen__debug__cpu() { ++ _arguments -s -S \ ++ '--entry=[Entry file for the worker]:entry:_files' \ ++ '--output=[Specify a path to generate the profile file]:output:' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' ++} ++ ++_shopify__hydrogen__debug() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'cpu:Builds and profiles the server startup time the app' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'hydrogen debug command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ cpu) _shopify__hydrogen__debug__cpu && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__hydrogen__deploy() { ++ _arguments -s -S \ ++ '--assets-dir=[Directory containing the client assets to deploy, relative to the project...]:assets-dir:' \ ++ '--auth-bypass-token[Generate an authentication bypass token, which can be used to perform...]' \ ++ '--auth-bypass-token-duration=[Specify the duration (in hours) up to 12 hours for the authentication...]:auth-bypass-token-duration:' \ ++ '--build-command=[Specify a build command to run before deploying]:build-command:' \ ++ '--entry=[Entry file for the worker]:entry:_files' \ ++ '(--env --env-branch)--env=[Specifies the environment to perform the operation using its handle]:env:' \ ++ '--env-branch=[Specifies the environment to perform the operation using its Git branch name]:env-branch:' \ ++ '--env-file=[Path to an environment file to override existing environment variables for...]:env-file:' \ ++ '(-f --force)'{-f,--force}'[Forces a deployment to proceed if there are uncommitted changes in its Git...]' \ ++ '--force-client-sourcemap[Client sourcemapping is avoided by default because it makes backend code...]' \ ++ '--json-output[Create a JSON file containing the deployment details in CI environments]' \ ++ '--lockfile-check[Checks that there is exactly one valid lockfile in the project]' \ ++ '--metadata-description=[Description of the changes in the deployment]:metadata-description:' \ ++ '--metadata-user=[User that initiated the deployment]:metadata-user:' \ ++ '--no-verify[Skip the routability verification step after deployment]' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '--preview[Deploys to the Preview environment]' \ ++ '(-s --shop)'{-s,--shop}'=[Shop URL]:shop:' \ ++ '(-t --token)'{-t,--token}'=[Oxygen deployment token]:token:' \ ++ '--worker-dir=[Directory containing the Oxygen worker entry point (`index.js` or...]:worker-dir:' ++} ++ ++_shopify__hydrogen__dev() { ++ _arguments -s -S \ ++ '--codegen[Automatically generates GraphQL types for your project’s Storefront API...]' \ ++ '--codegen-config-path=[Specifies a path to a codegen configuration file]:codegen-config-path:' \ ++ '--customer-account-push[Use tunneling for local development and push the tunneling domain to admin]' \ ++ '--debug[Enables inspector connections to the server with a debugger such as Visual...]' \ ++ '--disable-deps-optimizer[Disable adding dependencies to Vite'\''s `ssr.optimizeDeps.include`...]' \ ++ '--disable-version-check[Skip the version check when running `hydrogen dev`]' \ ++ '--disable-virtual-routes[Disable rendering fallback routes when a route file doesn'\''t exist]' \ ++ '--entry=[Entry file for the worker]:entry:_files' \ ++ '(--env --env-branch)--env=[Specifies the environment to perform the operation using its handle]:env:' \ ++ '--env-branch=[Specifies the environment to perform the operation using its Git branch name]:env-branch:' \ ++ '--env-file=[Path to an environment file to override existing environment variables]:env-file:' \ ++ '--host[Expose the server to the local network]' \ ++ '--inspector-port=[The port where the inspector is available]:inspector-port:' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '--port=[The port to run the server on]:port:' \ ++ '--verbose[Outputs more information about the command'\''s execution]' ++} ++ ++_shopify__hydrogen__env__list() { ++ _arguments -s -S \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' ++} ++ ++_shopify__hydrogen__env__pull() { ++ _arguments -s -S \ ++ '(--env --env-branch)--env=[Specifies the environment to perform the operation using its handle]:env:' \ ++ '--env-branch=[Specifies the environment to perform the operation using its Git branch name]:env-branch:' \ ++ '--env-file=[Path to an environment file to override existing environment variables]:env-file:' \ ++ '(-f --force)'{-f,--force}'[Overwrites the destination directory and files if they already exist]' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' ++} ++ ++_shopify__hydrogen__env__push() { ++ _arguments -s -S \ ++ '(--dry-run -f --force)--dry-run[Preview environment variable changes without pushing them]' \ ++ '--env=[Specifies the environment to perform the operation using its handle]:env:' \ ++ '--env-file=[Path to an environment file to override existing environment variables]:env-file:' \ ++ '(-f --force)'{-f,--force}'[Push environment variable changes without confirmation]' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' ++} ++ ++_shopify__hydrogen__env() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List the environments on your linked Hydrogen storefront' ++ 'pull:Populate your .env with variables from your Hydrogen storefront' ++ 'push:Push environment variables from the local .env file to your linked Hydrogen...' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'hydrogen env command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _shopify__hydrogen__env__list && ret=0 ;; ++ pull) _shopify__hydrogen__env__pull && ret=0 ;; ++ push) _shopify__hydrogen__env__push && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__hydrogen__generate__route() { ++ _arguments -s -S \ ++ '--adapter=[React Router adapter used in the route]:adapter:' \ ++ '(-f --force)'{-f,--force}'[Overwrites the destination directory and files if they already exist]' \ ++ '--locale-param=[The param name in Remix routes for the i18n locale, if any]:locale-param:' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '--typescript[Generate TypeScript files]' \ ++ '*:file:_files' ++} ++ ++_shopify__hydrogen__generate__routes() { ++ _arguments -s -S \ ++ '--adapter=[React Router adapter used in the route]:adapter:' \ ++ '(-f --force)'{-f,--force}'[Overwrites the destination directory and files if they already exist]' \ ++ '--locale-param=[The param name in Remix routes for the i18n locale, if any]:locale-param:' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '--typescript[Generate TypeScript files]' ++} ++ ++_shopify__hydrogen__generate() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'route:Generates a standard Shopify route' ++ 'routes:Generates all supported standard shopify routes' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'hydrogen generate command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ route) _shopify__hydrogen__generate__route && ret=0 ;; ++ routes) _shopify__hydrogen__generate__routes && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__hydrogen__init() { ++ _arguments -s -S \ ++ '(-f --force)'{-f,--force}'[Overwrites the destination directory and files if they already exist]' \ ++ '--git[Init Git and create initial commits]' \ ++ '--install-deps[Auto installs dependencies using the active package manager]' \ ++ '--language=[Sets the template language to use]:language:' \ ++ '--markets=[Sets the URL structure to support multiple markets]:markets:' \ ++ '--mock-shop[Use mock.shop as the data source for the storefront]' \ ++ '--path=[The path to the directory of the new Hydrogen storefront]:path:_files -/' \ ++ '--quickstart[Scaffolds a new Hydrogen project with a set of sensible defaults]' \ ++ '--shortcut[Creates a global h2 shortcut for Shopify CLI using shell aliases]' \ ++ '--styling=[Sets the styling strategy to use]:styling:' \ ++ '--template=[Scaffolds project based on an existing template or example from the...]:template:' ++} ++ ++_shopify__hydrogen__link() { ++ _arguments -s -S \ ++ '(--create-storefront --storefront)--create-storefront[Create a new Hydrogen storefront]' \ ++ '(-f --force)'{-f,--force}'[Overwrites the destination directory and files if they already exist]' \ ++ '(--name --storefront)--name=[The name to use when creating a new Hydrogen storefront]:name:' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '(-s --shop)'{-s,--shop}'=[Shop URL]:shop:' \ ++ '(--storefront --create-storefront --name)--storefront=[The name of a Hydrogen Storefront (e.g]:storefront:' ++} ++ ++_shopify__hydrogen__list() { ++ _arguments -s -S \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' ++} ++ ++_shopify__hydrogen__login() { ++ _arguments -s -S \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '(-s --shop)'{-s,--shop}'=[Shop URL]:shop:' ++} ++ ++_shopify__hydrogen__logout() { ++ _arguments -s -S \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' ++} ++ ++_shopify__hydrogen__preview() { ++ _arguments -s -S \ ++ '--build[Builds the app before starting the preview server]' \ ++ '--codegen[Automatically generates GraphQL types for your project’s Storefront API...]' \ ++ '--codegen-config-path=[Specifies a path to a codegen configuration file]:codegen-config-path:' \ ++ '--debug[Enables inspector connections to the server with a debugger such as Visual...]' \ ++ '--entry=[Entry file for the worker]:entry:_files' \ ++ '(--env --env-branch)--env=[Specifies the environment to perform the operation using its handle]:env:' \ ++ '--env-branch=[Specifies the environment to perform the operation using its Git branch name]:env-branch:' \ ++ '--env-file=[Path to an environment file to override existing environment variables]:env-file:' \ ++ '--inspector-port=[The port where the inspector is available]:inspector-port:' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '--port=[The port to run the server on]:port:' \ ++ '--verbose[Outputs more information about the command'\''s execution]' \ ++ '--watch[Watches for changes and rebuilds the project]' ++} ++ ++_shopify__hydrogen__setup__css() { ++ _arguments -s -S \ ++ '(-f --force)'{-f,--force}'[Overwrites the destination directory and files if they already exist]' \ ++ '--install-deps[Auto installs dependencies using the active package manager]' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '*:file:_files' ++} ++ ++_shopify__hydrogen__setup__markets() { ++ _arguments -s -S \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '*:file:_files' ++} ++ ++_shopify__hydrogen__setup__vite() { ++ _arguments -s -S \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' ++} ++ ++_shopify__hydrogen__setup() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'css:Setup CSS strategies for your project' ++ 'markets:Setup support for multiple markets in your project' ++ 'vite:EXPERIMENTAL\: Upgrades the project to use Vite' ++ ) ++ ++ _arguments -s -C \ ++ '(-f --force)'{-f,--force}'[Overwrites the destination directory and files if they already exist]' \ ++ '--install-deps[Auto installs dependencies using the active package manager]' \ ++ '--markets=[Sets the URL structure to support multiple markets]:markets:' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '--shortcut[Creates a global h2 shortcut for Shopify CLI using shell aliases]' \ ++ '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'hydrogen setup command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ css) _shopify__hydrogen__setup__css && ret=0 ;; ++ markets) _shopify__hydrogen__setup__markets && ret=0 ;; ++ vite) _shopify__hydrogen__setup__vite && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__hydrogen__shortcut() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify__hydrogen__unlink() { ++ _arguments -s -S \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' ++} ++ ++_shopify__hydrogen__upgrade() { ++ _arguments -s -S \ ++ '(-f --force)'{-f,--force}'[Ignore warnings and force the upgrade to the target version]' \ ++ '--path=[The path to the directory of the Hydrogen storefront]:path:_files -/' \ ++ '(-v --version)'{-v,--version}'=[A target hydrogen version to update to]:version:' ++} ++ ++_shopify__hydrogen() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'build:Builds a Hydrogen storefront for production' ++ 'check:Returns diagnostic information about a Hydrogen storefront' ++ 'codegen:Generate types for the Storefront API queries found in your project' ++ 'customer-account-push:Push project configuration to admin' ++ 'debug:Profile the storefront' ++ 'deploy:Builds and deploys a Hydrogen storefront to Oxygen' ++ 'dev:Runs Hydrogen storefront in an Oxygen worker for development' ++ 'env:Manage storefront environment variables' ++ 'generate:Generate standard Shopify routes' ++ 'init:Creates a new Hydrogen storefront' ++ 'link:Link a local project to one of your shop'\''s Hydrogen storefronts' ++ 'list:Returns a list of Hydrogen storefronts available on a given shop' ++ 'login:Login to your Shopify account' ++ 'logout:Logout of your local session' ++ 'preview:Runs a Hydrogen storefront in an Oxygen worker for production' ++ 'setup:Scaffold routes and core functionality' ++ 'shortcut:Creates a global `h2` shortcut for the Hydrogen CLI' ++ 'unlink:Unlink a local project from a Hydrogen storefront' ++ 'upgrade:Upgrade Remix and Hydrogen npm dependencies' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'hydrogen command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ build) _shopify__hydrogen__build && ret=0 ;; ++ check) _shopify__hydrogen__check && ret=0 ;; ++ codegen) _shopify__hydrogen__codegen && ret=0 ;; ++ customer-account-push) _shopify__hydrogen__customer_account_push && ret=0 ;; ++ debug) _shopify__hydrogen__debug && ret=0 ;; ++ deploy) _shopify__hydrogen__deploy && ret=0 ;; ++ dev) _shopify__hydrogen__dev && ret=0 ;; ++ env) _shopify__hydrogen__env && ret=0 ;; ++ generate) _shopify__hydrogen__generate && ret=0 ;; ++ init) _shopify__hydrogen__init && ret=0 ;; ++ link) _shopify__hydrogen__link && ret=0 ;; ++ list) _shopify__hydrogen__list && ret=0 ;; ++ login) _shopify__hydrogen__login && ret=0 ;; ++ logout) _shopify__hydrogen__logout && ret=0 ;; ++ preview) _shopify__hydrogen__preview && ret=0 ;; ++ setup) _shopify__hydrogen__setup && ret=0 ;; ++ shortcut) _shopify__hydrogen__shortcut && ret=0 ;; ++ unlink) _shopify__hydrogen__unlink && ret=0 ;; ++ upgrade) _shopify__hydrogen__upgrade && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__organization__list() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__organization() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List Shopify organizations you have access to' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'organization command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _shopify__organization__list && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__search() { ++ _arguments -s -S \ ++ '--no-color[Disable color output]' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '*:file:_files' ++} ++ ++_shopify__store__auth__list() { ++ _arguments -s -S \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__store__auth() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List stores authenticated directly with store auth' ++ ) ++ ++ _arguments -s -C \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--scopes=[Comma-separated Admin API scopes to request for the app]:scopes:' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store]:store:' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'store auth command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _shopify__store__auth__list && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__store__bulk__cancel() { ++ _arguments -s -S \ ++ '--id=[The bulk operation ID to cancel (numeric ID or full GID)]:id:' \ ++ '--no-color[Disable color output]' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__store__bulk__execute() { ++ _arguments -s -S \ ++ '--allow-mutations[Allow GraphQL mutations to run against the target store]' \ ++ '--no-color[Disable color output]' \ ++ '--output-file=[The file path where results should be written if --watch is specified]:output-file:' \ ++ '(-q --query)'{-q,--query}'=[The GraphQL query or mutation to run as a bulk operation]:query:' \ ++ '--query-file=[Path to a file containing the GraphQL query or mutation]:query-file:' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store]:store:' \ ++ '(--variable-file -v --variables)--variable-file=[Path to a file containing GraphQL variables in JSONL format (one JSON...]:variable-file:' \ ++ *''{-v,--variables}'=[The values for any GraphQL variables in your mutation, in JSON format]:variables:' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '--version=[The API version to use for the bulk operation]:version:' \ ++ '--watch[Wait for bulk operation results before exiting]' ++} ++ ++_shopify__store__bulk__status() { ++ _arguments -s -S \ ++ '--id=[The bulk operation ID (numeric ID or full GID)]:id:' \ ++ '--no-color[Disable color output]' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__store__bulk() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'cancel:Cancel a bulk operation on a store' ++ 'execute:Execute bulk operations on a store' ++ 'status:Check the status of bulk operations on a store' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'store bulk command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ cancel) _shopify__store__bulk__cancel && ret=0 ;; ++ execute) _shopify__store__bulk__execute && ret=0 ;; ++ status) _shopify__store__bulk__status && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__store__create__preview() { ++ _arguments -s -S \ ++ '--country=[Two-letter country code for the store, such as US, CA, or GB]:country:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--name=[The name of the store]:name:' \ ++ '--no-color[Disable color output]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__store__create() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'preview:Create a preview Shopify store' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'store create command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ preview) _shopify__store__create__preview && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__store__execute() { ++ _arguments -s -S \ ++ '--allow-mutations[Allow GraphQL mutations to run against the target store]' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--output-file=[The file name where results should be written, instead of STDOUT]:output-file:' \ ++ '(-q --query)'{-q,--query}'=[The GraphQL query or mutation, as a string]:query:' \ ++ '--query-file=[Path to a file containing the GraphQL query or mutation]:query-file:' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store]:store:' \ ++ '(--variable-file -v --variables)--variable-file=[Path to a file containing GraphQL variables in JSON format]:variable-file:' \ ++ '(-v --variables --variable-file)'{-v,--variables}'=[The values for any GraphQL variables in your query or mutation, in JSON...]:variables:' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '--version=[The API version to use for the query or mutation]:version:' ++} ++ ++_shopify__store__graphiql() { ++ _arguments -s -S \ ++ '--allow-mutations[Allow GraphQL mutations to run against the target store]' \ ++ '--no-color[Disable color output]' \ ++ '--port=[Local port for the GraphiQL server]:port:' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store]:store:' \ ++ '(-v --variables)'{-v,--variables}'=[The values for any GraphQL variables in your query or mutation, in JSON...]:variables:' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '--version=[The API version to use in GraphiQL]:version:' ++} ++ ++_shopify__store__info() { ++ _arguments -s -S \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__store__list() { ++ _arguments -s -S \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--organization-id=[The numeric organization ID]:organization-id:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__store__open() { ++ _arguments -s -S \ ++ '--no-color[Disable color output]' \ ++ '(-s --store)'{-s,--store}'=[The myshopify.com domain of the store]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__store() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'auth:Authenticate an app against a store for store commands' ++ 'bulk:Run bulk store operations' ++ 'create:Create a store' ++ 'execute:Execute GraphQL queries and mutations on a store' ++ 'graphiql:Open a local GraphiQL UI for a store' ++ 'info:Surface metadata about a Shopify store' ++ 'list:List stores in a Shopify organization' ++ 'open:Open your Shopify store in the default web browser' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'store command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ auth) _shopify__store__auth && ret=0 ;; ++ bulk) _shopify__store__bulk && ret=0 ;; ++ create) _shopify__store__create && ret=0 ;; ++ execute) _shopify__store__execute && ret=0 ;; ++ graphiql) _shopify__store__graphiql && ret=0 ;; ++ info) _shopify__store__info && ret=0 ;; ++ list) _shopify__store__list && ret=0 ;; ++ open) _shopify__store__open && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__theme__check() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(-a --auto-correct)'{-a,--auto-correct}'[Automatically fix offenses]' \ ++ '(-C --config)'{-C,--config}'=[Use the config provided, overriding .theme-check.yml if present]:config:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '--fail-level=[Minimum severity for exit with error code]:fail-level:(crash error suggestion style warning info)' \ ++ '--init[Generate a .theme-check.yml file]' \ ++ '--list[List enabled checks]' \ ++ '--no-color[Disable color output]' \ ++ '(-o --output)'{-o,--output}'=[The output format to use]:output:(text json)' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '--print[Output active config to STDOUT]' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '(-v --version)'{-v,--version}'[Print Theme Check version]' ++} ++ ++_shopify__theme__console() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--store-password=[The password for storefronts with password protection]:store-password:' \ ++ '--url=[The url to be used as context]:url:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__delete() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(-d --development)'{-d,--development}'[Delete your development theme]' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '(-f --force)'{-f,--force}'[Skip confirmation]' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-a --show-all)'{-a,--show-all}'[Include other development themes in the theme list]' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ *''{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__dev() { ++ _arguments -s -S \ ++ '(-a --allow-live)'{-a,--allow-live}'[Allow development on a live theme]' \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '--error-overlay=[Controls the visibility of the error overlay when an theme asset upload...]:error-overlay:(silent default)' \ ++ '--host=[Set which network interface the web server listens on]:host:_hosts' \ ++ *''{-x,--ignore}'=[Skip hot reloading any files that match the specified pattern]:ignore:_files' \ ++ '--listing=[The listing preset to use for multi-preset themes]:listing:' \ ++ '--live-reload=[The live reload mode switches the server behavior when a file is modified\:]:live-reload:(hot-reload full-page off)' \ ++ '--no-color[Disable color output]' \ ++ '(-n --nodelete)'{-n,--nodelete}'[Prevents files from being deleted in the remote theme when a file has been...]' \ ++ '--notify=[The file path or URL]:notify:_files' \ ++ *''{-o,--only}'=[Hot reload only files that match the specified pattern]:only:_files' \ ++ '--open[Automatically launch the theme preview in your default web browser]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '--port=[Local port to serve theme preview from]:port:' \ ++ '--reconciliation-strategy=[How to resolve JSON conflicts when --theme-editor-sync is enabled]:reconciliation-strategy:(keep-local keep-remote abort)' \ ++ '--standard-events-inspector[Inject the standard events inspector into storefront HTML]' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--store-password=[The password for storefronts with password protection]:store-password:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--theme-editor-sync[Synchronize Theme Editor updates in the local theme files]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__duplicate() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '(-f --force)'{-f,--force}'[Force the duplicate operation to run without prompts or confirmations]' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '(-n --name)'{-n,--name}'=[Name of the newly duplicated theme]:name:' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__info() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(-d --development)'{-d,--development}'[Retrieve info from your development theme]' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__init() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(-u --clone-url)'{-u,--clone-url}'=[The Git URL to clone from]:clone-url:' \ ++ '(-l --latest)'{-l,--latest}'[Downloads the latest release of the `clone-url`]' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '--verbose[Increase the verbosity of the output]' \ ++ '*:file:_files' ++} ++ ++_shopify__theme__language_server() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '--no-color[Disable color output]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__list() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '--id=[Only list theme with the given ID]:id:' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--name=[Only list themes that contain the given name]:name:' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '--role=[Only list themes with the given role]:role:(live unpublished development)' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__metafields__pull() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__metafields() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'pull:Download metafields definitions from your shop into a local file' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'theme metafields command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ pull) _shopify__theme__metafields__pull && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__theme__open() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(-d --development)'{-d,--development}'[Open your development theme]' \ ++ '(-E --editor)'{-E,--editor}'[Open the theme editor for the specified theme in the browser]' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '(-l --live)'{-l,--live}'[Open your live (published) theme]' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__package() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '--no-color[Disable color output]' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__preview() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '--json[Output the preview URL and identifier as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--open[Automatically launch the theme preview in your default web browser]' \ ++ '--overrides=[Path to a JSON overrides file]:overrides:' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '--preview-id=[An existing preview identifier to update instead of creating a new preview]:preview-id:' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__profile() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--store-password=[The password for storefronts with password protection]:store-password:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--url=[The url to be used as context]:url:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__publish() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '(-f --force)'{-f,--force}'[Skip confirmation]' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__pull() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(-d --development)'{-d,--development}'[Pull theme files from your remote development theme]' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ *''{-x,--ignore}'=[Skip downloading the specified files (Multiple flags allowed)]:ignore:_files' \ ++ '(-l --live)'{-l,--live}'[Pull theme files from your remote live theme]' \ ++ '--no-color[Disable color output]' \ ++ '(-n --nodelete)'{-n,--nodelete}'[Prevent deleting local files that don'\''t exist remotely]' \ ++ *''{-o,--only}'=[Download only the specified files (Multiple flags allowed)]:only:_files' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__push() { ++ _arguments -s -S \ ++ '(-a --allow-live)'{-a,--allow-live}'[Allow push to a live theme]' \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(-d --development)'{-d,--development}'[Push theme files from your remote development theme]' \ ++ '(-c --development-context -t --theme)'{-c,--development-context}'=[Unique identifier for a development theme context (e.g., PR number, branch...]:development-context:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ *''{-x,--ignore}'=[Skip uploading the specified files (Multiple flags allowed)]:ignore:_files' \ ++ '(-j --json)'{-j,--json}'[Output the result as JSON]' \ ++ '--listing=[The listing preset to use for multi-preset themes]:listing:' \ ++ '(-l --live)'{-l,--live}'[Push theme files from your remote live theme]' \ ++ '--no-color[Disable color output]' \ ++ '(-n --nodelete)'{-n,--nodelete}'[Prevent deleting remote files that don'\''t exist locally]' \ ++ *''{-o,--only}'=[Upload only the specified files (Multiple flags allowed)]:only:_files' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-p --publish)'{-p,--publish}'[Publish as the live theme after uploading]' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--strict[Require theme check to pass without errors before pushing]' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '(-u --unpublished)'{-u,--unpublished}'[Create a new unpublished theme and push to it]' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__rename() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ '(-d --development)'{-d,--development}'[Rename your development theme]' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '(-l --live)'{-l,--live}'[Rename your remote live theme]' \ ++ '(-n --name)'{-n,--name}'=[The new name for the theme]:name:' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '(-t --theme)'{-t,--theme}'=[Theme ID or name of the remote theme]:theme:_shopify_themes' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme__share() { ++ _arguments -s -S \ ++ '--auth-alias=[Alias of the Shopify account to use for authentication]:auth-alias:' \ ++ *''{-e,--environment}'=[The environment to apply to the current command]:environment:_shopify_environments' \ ++ '--listing=[The listing preset to use for multi-preset themes]:listing:' \ ++ '--no-color[Disable color output]' \ ++ '--password=[Password generated from the Theme Access app or an Admin API token]:password:' \ ++ '--path=[The path where you want to run the command]:path:_files -/' \ ++ '(-s --store)'{-s,--store}'=[Store URL]:store:' \ ++ '--verbose[Increase the verbosity of the output]' ++} ++ ++_shopify__theme() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'check:Validate the theme' ++ 'console:Shopify Liquid REPL (read-eval-print loop) tool' ++ 'delete:Delete remote themes from the connected store' ++ 'dev:Uploads the current theme as a development theme to the connected store,...' ++ 'duplicate:Duplicates a theme from your theme library' ++ 'info:Displays information about your theme environment, including your current...' ++ 'init:Clones a Git repository to use as a starting point for building a new theme' ++ 'language-server:Start a Language Server Protocol server' ++ 'list:Lists the themes in your store, along with their IDs and statuses' ++ 'metafields:Theme metafield operations' ++ 'open:Opens the preview of your remote theme' ++ 'package:Package your theme into a .zip file, ready to upload to the Online Store' ++ 'preview:Applies JSON overrides to a theme and returns a preview URL' ++ 'profile:Profile the Liquid rendering of a theme page' ++ 'publish:Set a remote theme as the live theme' ++ 'pull:Download your remote theme files locally' ++ 'push:Uploads your local theme files to the connected store, overwriting the...' ++ 'rename:Renames an existing theme' ++ 'share:Creates a shareable, unpublished, and new theme on your theme library with...' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'theme command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ check) _shopify__theme__check && ret=0 ;; ++ console) _shopify__theme__console && ret=0 ;; ++ delete) _shopify__theme__delete && ret=0 ;; ++ dev) _shopify__theme__dev && ret=0 ;; ++ duplicate) _shopify__theme__duplicate && ret=0 ;; ++ info) _shopify__theme__info && ret=0 ;; ++ init) _shopify__theme__init && ret=0 ;; ++ language-server) _shopify__theme__language_server && ret=0 ;; ++ list) _shopify__theme__list && ret=0 ;; ++ metafields) _shopify__theme__metafields && ret=0 ;; ++ open) _shopify__theme__open && ret=0 ;; ++ package) _shopify__theme__package && ret=0 ;; ++ preview) _shopify__theme__preview && ret=0 ;; ++ profile) _shopify__theme__profile && ret=0 ;; ++ publish) _shopify__theme__publish && ret=0 ;; ++ pull) _shopify__theme__pull && ret=0 ;; ++ push) _shopify__theme__push && ret=0 ;; ++ rename) _shopify__theme__rename && ret=0 ;; ++ share) _shopify__theme__share && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify__upgrade() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify__version() { ++ _arguments -s -S '*:file:_files' ++} ++ ++_shopify() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'app:Build Shopify apps' ++ 'auth:Authentication operations' ++ 'commands:List all shopify commands' ++ 'config:CLI configuration options' ++ 'doc:Search the Shopify documentation' ++ 'help:Display help for Shopify CLI' ++ 'hydrogen:Build Hydrogen storefronts' ++ 'organization:Work with your organizations' ++ 'search:Search shopify.dev for the most relevant content matching a query' ++ 'store:Work with a store' ++ 'theme:Build Liquid themes' ++ 'upgrade:Upgrades Shopify CLI' ++ 'version:Shopify CLI version currently installed' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'shopify command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ app) _shopify__app && ret=0 ;; ++ auth) _shopify__auth && ret=0 ;; ++ commands) _shopify__commands && ret=0 ;; ++ config) _shopify__config && ret=0 ;; ++ doc) _shopify__doc && ret=0 ;; ++ help) _shopify__help && ret=0 ;; ++ hydrogen) _shopify__hydrogen && ret=0 ;; ++ organization) _shopify__organization && ret=0 ;; ++ search) _shopify__search && ret=0 ;; ++ store) _shopify__store && ret=0 ;; ++ theme) _shopify__theme && ret=0 ;; ++ upgrade) _shopify__upgrade && ret=0 ;; ++ version) _shopify__version && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_shopify "$@" +diff --git a/plugins/shopify/shopify.plugin.zsh b/plugins/shopify/shopify.plugin.zsh +new file mode 100644 +index 00000000..e90fdae7 +--- /dev/null ++++ b/plugins/shopify/shopify.plugin.zsh +@@ -0,0 +1,203 @@ ++# Shopify CLI: completion, aliases and guard rails. ++# https://shopify.dev/docs/api/shopify-cli ++ ++if (( ! $+commands[shopify] )); then ++ return ++fi ++ ++# Prefer a project-local CLI: app and Hydrogen projects pin their own version. ++# The walk stops at $HOME so a stray ~/node_modules cannot hijack every project. ++# $commands avoids resolving back to the wrapper function below. ++function _shopify_bin() { ++ local dir="$PWD" ++ while [[ -n "$dir" && "$dir" != "/" && "$dir" != "$HOME" ]]; do ++ if [[ -x "$dir/node_modules/.bin/shopify" ]]; then ++ print -r -- "$dir/node_modules/.bin/shopify" ++ return 0 ++ fi ++ dir="${dir:h}" ++ done ++ print -r -- "$commands[shopify]" ++} ++ ++# Print the project type in $PWD: hydrogen, app or theme. ++# Hydrogen is tested first because those projects usually carry a ++# shopify.app.toml too. shopify.theme.toml is not a theme marker: it only ++# exists once environments are configured. ++function _shopify_project_type() { ++ local dir="$PWD" ++ local -a app_config ++ ++ while [[ -n "$dir" && "$dir" != "/" && "$dir" != "$HOME" ]]; do ++ if [[ -x "$dir/node_modules/.bin/h2" ]] || ++ [[ -r "$dir/package.json" && "$(<"$dir/package.json")" == *'"@shopify/hydrogen"'* ]]; then ++ return 0 ++ fi ++ ++ app_config=("$dir"/shopify.app*.toml(N)) ++ if (( $#app_config )); then ++ print -r -- app ++ return 0 ++ fi ++ ++ if [[ -f "$dir/config/settings_schema.json" && -f "$dir/layout/theme.liquid" ]]; then ++ print -r -- theme ++ return 0 ++ fi ++ ++ dir="${dir:h}" ++ done ++ ++ return 1 ++} ++ ++# Does this invocation need confirming? Sets REPLY to the reason. ++function _shopify_is_destructive() { ++ zstyle -T ':omz:plugins:shopify' confirm-destructive || return 1 ++ ++ # Nobody to answer: CI and pipelines are unaffected. ++ [[ -t 0 ]] || return 1 ++ ++ local topic="$1" subcommand="$2" arg ++ local -a long ++ local short="" ++ ++ # Short flags can be bundled, so collect them as characters: -al counts as l. ++ for arg in "${@[3,-1]}"; do ++ [[ "$arg" == "--" ]] && break ++ case "$arg" in ++ --*) long+=("${arg%%=*}") ;; ++ -?*) short+="${${arg%%=*}#-}" ;; ++ esac ++ done ++ ++ # An explicit force flag states the intent already. ++ if (( long[(I)--force] )) || [[ "$short" == *f* ]]; then ++ return 1 ++ fi ++ ++ case "$topic $subcommand" in ++ "theme push") ++ if (( long[(I)--live] || long[(I)--publish] )) || [[ "$short" == *[lp]* ]]; then ++ REPLY="this overwrites or publishes the live theme on the storefront." ++ return 0 ++ fi ++ ;; ++ "theme delete") ++ REPLY="deleting a theme cannot be undone." ++ return 0 ++ ;; ++ "app deploy") ++ if (( long[(I)--allow-deletes] )); then ++ REPLY="this can permanently remove app extensions." ++ return 0 ++ fi ++ ;; ++ esac ++ ++ return 1 ++} ++ ++# Adds a confirmation prompt before irreversible operations. Everything else ++# passes straight through, so `theme dev` stays interactive and pipes stay clean. ++function shopify() { ++ local REPLY ++ if _shopify_is_destructive "$@"; then ++ print -u2 -- "shopify: $REPLY" ++ if ! read -q "?Continue? [y/N] "; then ++ print -u2 -- "" ++ return 130 ++ fi ++ print -u2 -- "" ++ fi ++ ++ "$(_shopify_bin)" "$@" ++} ++ ++# Print the commands worth running in the current directory. ++function shopify_here() { ++ local project_type ++ project_type="$(_shopify_project_type)" ++ ++ case "$project_type" in ++ theme) ++ print -- "Shopify theme project." ++ print -- " shopify theme dev Preview locally with live reload" ++ print -- " shopify theme check Lint the theme" ++ print -- " shopify theme list List the themes on the store" ++ print -- " shopify theme pull Download a remote theme into this folder" ++ print -- " shopify theme push Upload this folder to a remote theme" ++ ;; ++ app) ++ print -- "Shopify app project." ++ print -- " shopify app dev Run the app against a development store" ++ print -- " shopify app info Show how the app is configured" ++ print -- " shopify app deploy Deploy the app and its extensions" ++ print -- " shopify app logs Stream app logs" ++ ;; ++ hydrogen) ++ print -- "Hydrogen storefront." ++ print -- " shopify hydrogen dev Run the storefront locally" ++ print -- " shopify hydrogen build Build for production" ++ print -- " shopify hydrogen deploy Deploy to Oxygen" ++ print -- " shopify hydrogen link Link this project to a storefront" ++ ;; ++ *) ++ print -- "No Shopify project found here." ++ print -- " shopify theme init Start a new theme" ++ print -- " shopify app init Start a new app" ++ print -- " shopify hydrogen init Start a new Hydrogen storefront" ++ ;; ++ esac ++} ++ ++# Run the dev server for whichever kind of project this is. ++function shopd() { ++ local project_type ++ if ! project_type="$(_shopify_project_type)"; then ++ print -u2 -- "shopd: not inside a Shopify theme, app or Hydrogen project." ++ return 1 ++ fi ++ shopify "$project_type" dev "$@" ++} ++ ++# Show what the current project is connected to. ++function shopi() { ++ local project_type ++ if ! project_type="$(_shopify_project_type)"; then ++ print -u2 -- "shopi: not inside a Shopify theme, app or Hydrogen project." ++ return 1 ++ fi ++ case "$project_type" in ++ hydrogen) shopify hydrogen list "$@" ;; ++ *) shopify "$project_type" info "$@" ;; ++ esac ++} ++ ++# Complete the helpers like the commands they stand in for. ++if (( $+functions[compdef] )); then ++ _shopd() { ++ local project_type ++ project_type="$(_shopify_project_type)" || return 1 ++ words=(shopify "$project_type" dev ${words[2,-1]}) ++ (( CURRENT += 2 )) ++ _shopify ++ } ++ ++ _shopi() { ++ local project_type ++ project_type="$(_shopify_project_type)" || return 1 ++ if [[ "$project_type" == hydrogen ]]; then ++ words=(shopify hydrogen list ${words[2,-1]}) ++ else ++ words=(shopify "$project_type" info ${words[2,-1]}) ++ fi ++ (( CURRENT += 2 )) ++ _shopify ++ } ++ ++ compdef _shopd shopd ++ compdef _shopi shopi ++fi ++ ++alias shop='shopify' diff --git a/tasks/ohmyzsh__ohmyzsh-14037/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14037/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6ac8c63f4135abbe94242e9be3350cba3f3d4ed8 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14037/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 3f84a2ae4ab63343890ff90efca6d18b7292dd0f > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14037/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14037/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14037/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14038/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14038/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..398c58299f69e432ec4248a10b91a40b4ebf0386 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14038/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b842e5e63e90918356b947b3090ceeec549f48b9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b842e5e63e90918356b947b3090ceeec549f48b9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b842e5e63e90918356b947b3090ceeec549f48b9 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14038/instruction.md b/tasks/ohmyzsh__ohmyzsh-14038/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ef8422cf819ceea4b94c3a2fc565394c6aaf1145 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14038/instruction.md @@ -0,0 +1,50 @@ +# Issue + +**Title:** feat(appsignal-cli): add plugin for AppSignal + +## Description + +Adds a plugin for the [AppSignal CLI](https://docs.appsignal.com/cli) (`appsignal-cli`), the Rust binary AppSignal released this year for querying incidents, logs and traces from the terminal. + +It ships no completion generator of its own: there is no `appsignal-cli completions` command, it does not depend on `clap_complete`, and it has no machine-readable command dump. So `_appsignal-cli` is written from its command definitions and checked in, the way `plugins/cdk`, `plugins/terraform` and `plugins/shopify` already do. It targets AppSignal CLI 2.1.x. + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- **Completion** for all 11 topics and their subcommands, with the CLI's own descriptions at every level, and their flags and allowed values: incident states and severities, sort orders, log severities, trigger fields and comparison operators, output formats, skill targets. `samples` and `sample` complete like `traces`, as they do in the CLI itself. +- **`--org` completes offline** from the `org` key of the project's `.appsignal.toml`, found by walking up to the git root the way the CLI resolves it, and of the global config. +- **`--app`, `--app-id` and `--environment` complete from the account**, via `appsignal-cli apps list --output json`, showing each app's name and environment next to its ID. Off by default behind `zstyle ':omz:plugins:appsignal-cli' dynamic-app-completion yes`, because it needs authentication and makes a network call on Tab. Results are cached for five minutes. Parsed in zsh, so there is no dependency on `jq`. +- **Three aliases**: `asig` for the CLI itself, `aslog` for `logs tail` and `asinc` for `incidents list`. Those two are the commands people run repeatedly during an incident, and both complete like the command they stand in for, so `aslog --` offers the flags of `logs tail`. +- **A confirmation prompt** before four operations the CLI performs without asking: `logs metrics delete`, `logs triggers delete`, `triggers archive` (which also closes the trigger's alerts and incidents), and `incidents update --state CLOSED` when it names more than one incident, since that flag takes a comma-separated list. Skipped when stdin is not a terminal, so scripts and CI are unaffected, and disabled entirely with `zstyle ':omz:plugins:appsignal-cli' confirm-destructive no`. + +## Screenshot + +image + + +## Other comments: + +The plugin deliberately does **not** claim the bare `appsignal` name. The AppSignal Ruby gem installs its own `appsignal` command (`install`, `diagnose`, `demo`), which is what people run inside their apps; shadowing it would break those projects. Only `appsignal-cli` is wrapped and completed. + +**Testing.** The command surface was checked against the installed binary's `--help` tree across 52 command paths, so every flag the CLI reports is present in the completion. The destructive-command detection has a 17-case table covering the global `--output` flag appearing before the subcommand, `--number=7,8`, `--number 4 5 6`, single-incident closes that should stay quiet, and an app literally named `delete`. The dynamic completion helpers were run against a real account (37 apps), including the cache path. + +**AI disclosure.** The plugin was written with Claude Code, driven and reviewed by me. Two bugs it caught during testing are worth naming, since the same shapes exist elsewhere in the repo: the CLI pretty-prints its JSON, so the split-on-`{` parsing used in `plugins/shopify` returns only partial results until the payload is flattened first; and `_describe` takes the *name* of an array, not its values. + +🤖 Co-authored with Claude Code + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b842e5e63e90`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14038/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14038/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..fc82542e447c7d85037f361e2c5330360c79a2a8 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14038/solution/patch.diff @@ -0,0 +1,1328 @@ +diff --git a/plugins/appsignal-cli/README.md b/plugins/appsignal-cli/README.md +new file mode 100644 +index 00000000..16b6587d +--- /dev/null ++++ b/plugins/appsignal-cli/README.md +@@ -0,0 +1,122 @@ ++# AppSignal CLI plugin ++ ++This plugin adds aliases, guard rails and completion for the ++[AppSignal CLI](https://docs.appsignal.com/cli). ++ ++To use it, add `appsignal-cli` to the plugins array in your zshrc file: ++ ++```zsh ++plugins=(... appsignal-cli) ++``` ++ ++## Requirements ++ ++[AppSignal CLI](https://docs.appsignal.com/cli) 2.1 or newer, installed and on ++your `PATH`. The plugin does nothing if it is not: ++ ++```zsh ++brew install appsignal/appsignal-cli/appsignal-cli ++# or ++curl -sSL https://github.com/appsignal/appsignal-cli/releases/latest/download/install.sh | sudo sh ++``` ++ ++Most commands need `appsignal-cli auth login` first. ++ ++## Aliases ++ ++| Alias | Command | Description | ++| :------ | :----------------------------- | :--------------------------------- | ++| `asig` | `appsignal-cli` | The AppSignal CLI itself | ++| `aslog` | `appsignal-cli logs tail` | Stream log lines as they arrive | ++| `asinc` | `appsignal-cli incidents list` | List incidents for an application | ++ ++`aslog` and `asinc` complete like the commands they stand in for, so ++`aslog --` offers the flags of `appsignal-cli logs tail`. ++ ++## Functions ++ ++| Function | Description | ++| :-------------- | :----------------------------------------------------------------- | ++| `appsignal-cli` | Wraps the CLI to confirm before irreversible commands. See Settings | ++ ++## Completion ++ ++Every command completes with a description of what it does, at every level, and ++so do their flags and allowed values: incident states and severities, sort ++orders, log severities, trigger fields and comparison operators, output formats ++and skill targets. `samples` and `sample` complete like `traces`, as they do in ++the CLI itself. ++ ++`--org` completes offline from the `org` key of your project's ++`.appsignal.toml` and of the global config. ++ ++The AppSignal CLI ships no completion generator of its own, so `_appsignal-cli` ++is written from its command definitions and kept in this repository. It targets ++AppSignal CLI 2.1.x. ++ ++## Settings ++ ++Set these with `zstyle` in your zshrc, before Oh My Zsh is sourced. ++ ++### Confirming destructive commands ++ ++```zsh ++zstyle ':omz:plugins:appsignal-cli' confirm-destructive no ++``` ++ ++By default the plugin asks for confirmation before four operations that the CLI ++itself performs without a prompt: ++ ++- `appsignal-cli logs metrics delete` ++- `appsignal-cli logs triggers delete` ++- `appsignal-cli triggers archive`, which also closes the trigger's alerts and ++ incidents ++- `appsignal-cli incidents update --state CLOSED` when it names more than one ++ incident, since that flag accepts a comma-separated list ++ ++Nothing else is intercepted, and the prompt is skipped when stdin is not a ++terminal, so scripts, pipelines and CI are unaffected. Set the style to `no` to ++turn the prompt off entirely, or run `command appsignal-cli` for a single ++invocation. ++ ++### Completing applications ++ ++```zsh ++zstyle ':omz:plugins:appsignal-cli' dynamic-app-completion yes ++``` ++ ++Off by default. When enabled, `--app`, `--app-id` and `--environment` are ++completed from `appsignal-cli apps list --output json`, showing each ++application's name and environment next to its ID instead of making you copy ++IDs by hand. It is opt-in because it runs the CLI and makes a network call when ++you press Tab, and because it needs you to be authenticated. Results ++are cached for five minutes. ++ ++### Disabling the aliases ++ ++This works for every Oh My Zsh plugin: ++ ++```zsh ++zstyle ':omz:plugins:appsignal-cli' aliases no ++``` ++ ++## Caveats ++ ++- `appsignal-cli` and the AppSignal Ruby gem's `appsignal` command are different ++ tools. The gem's command installs and diagnoses the agent inside your app; ++ this one queries your data. The plugin deliberately leaves `appsignal` alone, ++ so it keeps working in projects that use the gem. ++- `appsignal-cli` is a shell function here. Run `command appsignal-cli` to reach ++ the binary directly. ++- Most commands need exactly one of `--app-id` or `--app`. `--environment` only ++ narrows `--app`; it does nothing next to `--app-id`. ++- `appsignal-cli project init` writes `.appsignal.toml`, and `auth login` then ++ stores OAuth tokens in it. Do not commit that file. ++- `incidents delete-note`, `auth logout` and the `--clear-*` flags of ++ `logs metrics update` and `logs triggers update` are destructive too, but are ++ not prompted for: each affects a single note, login or field. ++- `triggers create` and `triggers update` have their own `--format`, for the ++ format of the metric value. Everywhere else `--format` is a synonym for ++ `--output`. ++- The CLI sends usage telemetry by default. `APPSIGNAL_CLI_TELEMETRY=0` turns it ++ off, and `APPSIGNAL_CLI_DEBUG=1` shows internal errors. +diff --git a/plugins/appsignal-cli/_appsignal-cli b/plugins/appsignal-cli/_appsignal-cli +new file mode 100644 +index 00000000..138570d8 +--- /dev/null ++++ b/plugins/appsignal-cli/_appsignal-cli +@@ -0,0 +1,1080 @@ ++#compdef appsignal-cli ++ ++# Completion for the AppSignal CLI. https://docs.appsignal.com/cli ++# ++# Targets AppSignal CLI 2.1.x. The CLI has no `completions` command, no ++# clap_complete and no machine-readable command dump, so this is written from ++# its command definitions and kept here. Nothing runs the CLI at completion ++# time unless app completion is enabled below. ++ ++# Organization slugs from the TOML config. Offline, always enabled. ++# The CLI reads .appsignal.toml from the current directory upwards, stopping at ++# the git root, and falls back to the global config. ++_appsignal_cli_orgs() { ++ setopt localoptions extendedglob ++ local -a orgs files ++ local dir file line ++ # (#b) backreferences set $match, which would otherwise be left global. ++ local MATCH MBEGIN MEND ++ local -a match mbegin mend ++ ++ dir="$PWD" ++ while [[ -n "$dir" && "$dir" != "/" ]]; do ++ files+=("$dir/.appsignal.toml") ++ [[ -e "$dir/.git" ]] && break ++ dir="${dir:h}" ++ done ++ files+=("${XDG_CONFIG_HOME:-$HOME/.config}/appsignal/config.toml") ++ files+=("$HOME/Library/Application Support/appsignal/config.toml") ++ ++ for file in $files; do ++ [[ -r "$file" ]] || continue ++ for line in ${(f)"$(< $file)"}; do ++ [[ $line == (#b)[[:space:]]#org[[:space:]]#=[[:space:]]#\"([^\"]##)\"* ]] && orgs+=("$match[1]") ++ done ++ done ++ ++ orgs=(${(u)orgs}) ++ (( $#orgs )) || return 1 ++ _describe -t orgs 'organization' orgs ++} ++ ++# One tab-separated record per app, in $apps. Off by default: needs ++# `appsignal-cli auth login` and makes a network call on TAB. Enable with: ++# zstyle ':omz:plugins:appsignal-cli' dynamic-app-completion yes ++_appsignal_cli_app_cache() { ++ zstyle -t ':omz:plugins:appsignal-cli' dynamic-app-completion || return 1 ++ ++ local cache_file="${ZSH_CACHE_DIR:-$HOME/.cache}/appsignal-cli-apps" ++ local -a fresh ++ local json split entry id name environment ++ # $match and friends are set by =~ and would otherwise be left global. ++ local MATCH MBEGIN MEND ++ local -a match mbegin mend ++ local nl=$'\n' tab=$'\t' ++ ++ # Reuse the cached list for five minutes. ++ fresh=(${cache_file}(Nms-300)) ++ if (( $#fresh )); then ++ apps=("${(@f)$(< "$cache_file")}") ++ (( $#apps )) ++ return ++ fi ++ ++ json="$(command appsignal-cli apps list --output json 2>/dev/null)" || return 1 ++ # The CLI pretty-prints its JSON, so flatten it first, then take one chunk ++ # per object. Done in zsh so there is no dependency on jq. ++ json="${json//$nl/ }" ++ split="${json//\{/$nl}" ++ for entry in ${(f)split}; do ++ id="" name="" environment="" ++ [[ $entry =~ '"id":[[:space:]]*"([^"]*)"' ]] && id=$match[1] ++ [[ $entry =~ '"name":[[:space:]]*"([^"]*)"' ]] && name=$match[1] ++ [[ $entry =~ '"environment":[[:space:]]*"([^"]*)"' ]] && environment=$match[1] ++ [[ -n $id && -n $name ]] || continue ++ apps+=("${id}${tab}${name}${tab}${environment}") ++ done ++ ++ (( $#apps )) || return 1 ++ print -rl -- $apps > "$cache_file" 2>/dev/null ++} ++ ++# Application names. ++_appsignal_cli_apps() { ++ local -a apps names ++ local entry name ++ _appsignal_cli_app_cache || return 1 ++ for entry in $apps; do ++ name="${${(@ps:\t:)entry}[2]}" ++ names+=("${name//:/\\:}") ++ done ++ names=(${(u)names}) ++ _describe -t apps 'application' names ++} ++ ++# Application IDs, described by name and environment. ++_appsignal_cli_app_ids() { ++ local -a apps ids ++ local entry id name environment ++ _appsignal_cli_app_cache || return 1 ++ for entry in $apps; do ++ id="${${(@ps:\t:)entry}[1]}" ++ name="${${(@ps:\t:)entry}[2]}" ++ environment="${${(@ps:\t:)entry}[3]}" ++ ids+=("${id}:${name//:/ }${environment:+ (${environment})}") ++ done ++ _describe -t app-ids 'application' ids ++} ++ ++# Environments seen across the account's apps. ++_appsignal_cli_environments() { ++ local -a apps environments ++ local entry environment ++ _appsignal_cli_app_cache || return 1 ++ for entry in $apps; do ++ environment="${${(@ps:\t:)entry}[3]}" ++ [[ -n $environment ]] && environments+=("${environment//:/\\:}") ++ done ++ (( $#environments )) || return 1 ++ environments=(${(u)environments}) ++ _describe -t environments 'environment' environments ++} ++ ++# Log severity levels, as a comma-separated list. ++_appsignal_cli_severities() { ++ _values -s , 'severity' UNKNOWN TRACE DEBUG INFO NOTICE WARN ERROR CRITICAL ALERT FATAL ++} ++ ++# The global flags, and the app reference group carried by most data commands. ++# Filled into caller-local arrays so the specs are written once, not forty times. ++_appsignal_cli_base_args() { ++ base_args=( ++ '(- *)'{-h,--help}'[Print help]' ++ '(-o --output --format)'{-o,--output,--format}'=[Output format for command results]:format:(human json)' ++ ) ++} ++ ++_appsignal_cli_app_args() { ++ app_args=( ++ '--app-id=[Application ID, an alternative to --app plus --environment]:app id:_appsignal_cli_app_ids' ++ '--app=[Application name, used with optional --environment to find the app]:app:_appsignal_cli_apps' ++ '--environment=[Environment filter, for example production]:environment:_appsignal_cli_environments' ++ '--org=[Organization slug, uses the saved default if omitted]:org:_appsignal_cli_orgs' ++ ) ++} ++ ++_appsignal_cli__about() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args ++} ++ ++_appsignal_cli__auth__login() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args \ ++ '--endpoint=[Override the AppSignal base URL]:url:_urls' \ ++ '--rest-endpoint=[Override the AppSignal REST API base URL]:url:_urls' \ ++ '--oauth-client-id=[Override the OAuth client ID used during login]:client id:' \ ++ '--org=[Set the default organization slug during login]:org:_appsignal_cli_orgs' ++} ++ ++_appsignal_cli__auth__logout() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args ++} ++ ++_appsignal_cli__auth__status() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args ++} ++ ++_appsignal_cli__auth() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'login:Authenticate with AppSignal via OAuth' ++ 'logout:Remove stored credentials' ++ 'status:Show the current authentication status' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'auth command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ login) _appsignal_cli__auth__login && ret=0 ;; ++ logout) _appsignal_cli__auth__logout && ret=0 ;; ++ status) _appsignal_cli__auth__status && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal_cli__apps__list() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args ++} ++ ++_appsignal_cli__apps__info() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args \ ++ '--app-id=[The application ID]:app id:_appsignal_cli_app_ids' ++} ++ ++_appsignal_cli__apps__find() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args \ ++ '--name=[Application name, case-insensitive]:name:_appsignal_cli_apps' \ ++ '--environment=[Environment filter, for example production]:environment:_appsignal_cli_environments' \ ++ '--org=[Organization slug, uses the saved default if omitted]:org:_appsignal_cli_orgs' ++} ++ ++_appsignal_cli__apps__set_org() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args \ ++ '--org=[Organization slug]:org:_appsignal_cli_orgs' ++} ++ ++_appsignal_cli__apps__show_org() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args ++} ++ ++_appsignal_cli__apps__resources__any() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args ++} ++ ++_appsignal_cli__apps__resources() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'all:Show all supported app resources' ++ 'users:Show app users' ++ 'notifiers:Show app notifiers' ++ 'namespaces:Show app namespaces' ++ 'dashboards:Show app dashboards' ++ 'deploy-markers:Show recent deploy markers' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'apps resources command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ all|users|notifiers|namespaces|dashboards|deploy-markers) ++ _appsignal_cli__apps__resources__any && ret=0 ++ ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal_cli__apps() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List all applications for the organization attached to the current OAuth token' ++ 'info:Show details for a specific application by ID' ++ 'find:Find an application by name and optional environment' ++ 'set-org:Set the default organization slug' ++ 'show-org:Show the current default organization' ++ 'resources:Show resources for an app' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'apps command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _appsignal_cli__apps__list && ret=0 ;; ++ info) _appsignal_cli__apps__info && ret=0 ;; ++ find) _appsignal_cli__apps__find && ret=0 ;; ++ set-org) _appsignal_cli__apps__set_org && ret=0 ;; ++ show-org) _appsignal_cli__apps__show_org && ret=0 ;; ++ resources) _appsignal_cli__apps__resources && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal_cli__project__init() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args \ ++ '--endpoint=[Override the AppSignal base URL]:url:_urls' \ ++ '--rest-endpoint=[Override the AppSignal REST API base URL]:url:_urls' \ ++ '--oauth-client-id=[Override the OAuth client ID for this project]:client id:' \ ++ '--org=[Set the default organization slug for this project]:org:_appsignal_cli_orgs' ++} ++ ++_appsignal_cli__project() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'init:Create or update the project-local .appsignal.toml' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'project command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ init) _appsignal_cli__project__init && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++# Shared by every `incidents list*` command. ++_appsignal_cli_incident_list_args() { ++ incident_list_args=( ++ '--limit=[Maximum number of incidents to return]:limit:' ++ '--offset=[Offset for pagination]:offset:' ++ '--state=[Filter by state]:state:(OPEN CLOSED WIP)' ++ '--order=[Sort order, LAST for most recent activity or ID for creation order]:order:(LAST ID)' ++ ) ++} ++ ++_appsignal_cli__incidents__list() { ++ local -a base_args app_args incident_list_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _appsignal_cli_incident_list_args ++ _arguments -s -S $base_args $app_args $incident_list_args \ ++ '--namespaces=[Filter by namespaces, comma-separated, for example web,background]:namespaces:' \ ++ '--action=[Filter by action name, for example UsersController#show]:action:' ++} ++ ++_appsignal_cli__incidents__list_exceptions() { ++ local -a base_args app_args incident_list_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _appsignal_cli_incident_list_args ++ _arguments -s -S $base_args $app_args $incident_list_args \ ++ '--namespaces=[Filter by namespaces, comma-separated, for example web,background]:namespaces:' \ ++ '--action=[Filter by action name, for example UsersController#show]:action:' \ ++ '--query=[Search query to filter exception incidents by name or message]:query:' ++} ++ ++_appsignal_cli__incidents__list_performance() { ++ local -a base_args app_args incident_list_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _appsignal_cli_incident_list_args ++ _arguments -s -S $base_args $app_args $incident_list_args \ ++ '--namespaces=[Filter by namespaces, comma-separated, for example web,background]:namespaces:' \ ++ '--action=[Filter by action name, for example UsersController#show]:action:' \ ++ '--query=[Search query to filter performance incidents by action name]:query:' ++} ++ ++_appsignal_cli__incidents__list_anomalies() { ++ local -a base_args app_args incident_list_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _appsignal_cli_incident_list_args ++ _arguments -s -S $base_args $app_args $incident_list_args ++} ++ ++_appsignal_cli__incidents__show() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--number=[Incident number]:number:' ++} ++ ++_appsignal_cli__incidents__update() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '*--number=[Incident number, repeat or pass a comma-separated list for bulk state changes]:number:' \ ++ '--state=[New state]:state:(OPEN CLOSED WIP)' \ ++ '--severity=[New severity]:severity:(UNTRIAGED CRITICAL HIGH LOW NONE INFORMATIONAL)' \ ++ '--notification-frequency=[How often to notify about this incident]:frequency:(ALWAYS NEVER FIRST_IN_DEPLOY FIRST_AFTER_CLOSE NTH_IN_HOUR NTH_IN_DAY)' \ ++ '--notification-threshold=[Threshold for the NTH_IN_HOUR and NTH_IN_DAY frequencies]:threshold:' \ ++ '--assign=[Comma-separated user names or IDs to add as assignees]:assignees:' \ ++ '--assign-me[Assign the incident to the authenticated CLI user]' \ ++ '--unassign=[Comma-separated user names or IDs to remove from assignees]:assignees:' \ ++ '--description=[New description]:description:' ++} ++ ++_appsignal_cli__incidents__add_note() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--number=[Incident number]:number:' \ ++ '--content=[Note content, markdown supported]:content:' ++} ++ ++_appsignal_cli__incidents__list_notes() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--number=[Incident number]:number:' ++} ++ ++_appsignal_cli__incidents__update_note() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--number=[Incident number]:number:' \ ++ '--id=[ID of the note to update]:note id:' \ ++ '--content=[Note content, markdown supported]:content:' ++} ++ ++_appsignal_cli__incidents__delete_note() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--number=[Incident number]:number:' \ ++ '--id=[ID of the note to delete]:note id:' ++} ++ ++_appsignal_cli__incidents() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List incidents for an application (all types)' ++ 'list-exceptions:List exception incidents (with text search support)' ++ 'list-performance:List performance incidents (with text search support)' ++ 'list-anomalies:List anomaly detection incidents' ++ 'show:Show details for a specific incident by number' ++ 'update:Update an incident (state, severity, notification frequency, assignees)' ++ 'add-note:Add a note to an incident' ++ 'list-notes:List notes on an incident, including their IDs' ++ 'update-note:Update one of your notes on an incident' ++ 'delete-note:Delete one of your notes from an incident' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'incidents command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _appsignal_cli__incidents__list && ret=0 ;; ++ list-exceptions) _appsignal_cli__incidents__list_exceptions && ret=0 ;; ++ list-performance) _appsignal_cli__incidents__list_performance && ret=0 ;; ++ list-anomalies) _appsignal_cli__incidents__list_anomalies && ret=0 ;; ++ show) _appsignal_cli__incidents__show && ret=0 ;; ++ update) _appsignal_cli__incidents__update && ret=0 ;; ++ add-note) _appsignal_cli__incidents__add_note && ret=0 ;; ++ list-notes) _appsignal_cli__incidents__list_notes && ret=0 ;; ++ update-note) _appsignal_cli__incidents__update_note && ret=0 ;; ++ delete-note) _appsignal_cli__incidents__delete_note && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++# Shared by `logs tail` and `logs search`. ++_appsignal_cli_log_filter_args() { ++ log_filter_args=( ++ '--query=[Log query filter, supports field filters and free text]:query:' ++ '--severities=[Comma-separated severity levels, for example ERROR,CRITICAL]:severities:_appsignal_cli_severities' ++ '--source-ids=[Comma-separated source IDs to filter by]:source ids:' ++ '--view=[Log view name or ID, applies the saved filters of the view as defaults]:view:' ++ ) ++} ++ ++_appsignal_cli__logs__tail() { ++ local -a base_args app_args log_filter_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _appsignal_cli_log_filter_args ++ _arguments -s -S $base_args $app_args $log_filter_args ++} ++ ++_appsignal_cli__logs__search() { ++ local -a base_args app_args log_filter_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _appsignal_cli_log_filter_args ++ _arguments -s -S $base_args $app_args $log_filter_args \ ++ '--start=[Start time, ISO 8601]:timestamp:' \ ++ '--end=[End time, ISO 8601]:timestamp:' \ ++ '(--page-all)--limit=[Maximum number of log lines to return, at most 100]:limit:' \ ++ '(--page-all)--order=[Sort order, ASC for oldest first or DESC for newest first]:order:(ASC DESC)' \ ++ '(--limit --order)--page-all[Paginate to fetch all results, requires --start]' ++} ++ ++_appsignal_cli__logs__views() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args ++} ++ ++_appsignal_cli__logs__sources() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args ++} ++ ++_appsignal_cli__logs__metrics__list() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args ++} ++ ++_appsignal_cli__logs__metrics__create() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--name=[Metric configuration name]:name:' \ ++ '--query=[Query expression to match against log lines]:query:' \ ++ '*--source-id=[Scope the metric to a source ID, repeat to add more]:source id:' \ ++ '*--metric=[Metric definition in key=value form, for example name=log.error_count,type=counter]:metric:' ++} ++ ++_appsignal_cli__logs__metrics__update() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--id=[ID of the metric to update]:metric id:' \ ++ '--name=[Metric configuration name]:name:' \ ++ '--query=[Query expression to match against log lines]:query:' \ ++ '(--clear-sources)*--source-id=[Scope the metric to a source ID, repeat to add more]:source id:' \ ++ '(--source-id)--clear-sources[Remove every source from the metric]' \ ++ '(--clear-metrics)*--metric=[Metric definition in key=value form]:metric:' \ ++ '(--metric)--clear-metrics[Remove every metric definition]' ++} ++ ++_appsignal_cli__logs__metrics__delete() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--id=[ID of the metric to delete]:metric id:' ++} ++ ++_appsignal_cli__logs__metrics() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List log-derived metrics for an app' ++ 'create:Create a new log-derived metric' ++ 'update:Update a log-derived metric' ++ 'delete:Delete a log-derived metric' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'logs metrics command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _appsignal_cli__logs__metrics__list && ret=0 ;; ++ create) _appsignal_cli__logs__metrics__create && ret=0 ;; ++ update) _appsignal_cli__logs__metrics__update && ret=0 ;; ++ delete) _appsignal_cli__logs__metrics__delete && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal_cli__logs__triggers__list() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args ++} ++ ++_appsignal_cli__logs__triggers__create() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--name=[Trigger name]:name:' \ ++ '--query=[Query expression to match against log lines]:query:' \ ++ '*--source-id=[Scope the trigger to a source ID, repeat to add more]:source id:' \ ++ '--description=[Optional description shown with the trigger]:description:' \ ++ '*--notifier-id=[Notifier to alert, repeat to add more]:notifier id:' \ ++ '*--severity=[Match only this severity, repeat to add more]:severity:(UNKNOWN TRACE DEBUG INFO NOTICE WARN ERROR CRITICAL ALERT FATAL)' ++} ++ ++_appsignal_cli__logs__triggers__update() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--id=[ID of the trigger to update]:trigger id:' \ ++ '--name=[Trigger name]:name:' \ ++ '--query=[Query expression to match against log lines]:query:' \ ++ '(--clear-sources)*--source-id=[Scope the trigger to a source ID, repeat to add more]:source id:' \ ++ '(--source-id)--clear-sources[Remove every source from the trigger]' \ ++ '(--clear-description)--description=[Optional description shown with the trigger]:description:' \ ++ '(--description)--clear-description[Remove the description]' \ ++ '(--clear-notifiers)*--notifier-id=[Notifier to alert, repeat to add more]:notifier id:' \ ++ '(--notifier-id)--clear-notifiers[Remove every notifier from the trigger]' \ ++ '(--clear-severities)*--severity=[Match only this severity, repeat to add more]:severity:(UNKNOWN TRACE DEBUG INFO NOTICE WARN ERROR CRITICAL ALERT FATAL)' \ ++ '(--severity)--clear-severities[Match every severity]' ++} ++ ++_appsignal_cli__logs__triggers__delete() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--id=[ID of the trigger to delete]:trigger id:' ++} ++ ++_appsignal_cli__logs__triggers() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List log-based triggers for an app' ++ 'create:Create a new log-based trigger' ++ 'update:Update an existing log-based trigger' ++ 'delete:Delete a log-based trigger' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'logs triggers command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _appsignal_cli__logs__triggers__list && ret=0 ;; ++ create) _appsignal_cli__logs__triggers__create && ret=0 ;; ++ update) _appsignal_cli__logs__triggers__update && ret=0 ;; ++ delete) _appsignal_cli__logs__triggers__delete && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal_cli__logs() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'tail:Tail (stream) log lines in real time, with optional filters' ++ 'search:Search log lines (one-shot query)' ++ 'views:List saved log views (filter presets) for an app' ++ 'sources:List log sources for an app' ++ 'metrics:Create and manage log-derived metrics' ++ 'triggers:Create and manage log-based triggers' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'logs command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ tail) _appsignal_cli__logs__tail && ret=0 ;; ++ search) _appsignal_cli__logs__search && ret=0 ;; ++ views) _appsignal_cli__logs__views && ret=0 ;; ++ sources) _appsignal_cli__logs__sources && ret=0 ;; ++ metrics) _appsignal_cli__logs__metrics && ret=0 ;; ++ triggers) _appsignal_cli__logs__triggers && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal_cli__traces__list() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--namespace=[Namespace to search in, for example web, background, graphql]:namespace:' \ ++ '--action=[Action name to fetch traces for, for example UsersController#show]:action:' \ ++ '--start=[Start time, ISO 8601, defaults to 24 hours ago]:timestamp:' \ ++ '--end=[End time, ISO 8601, defaults to now]:timestamp:' \ ++ '--min-duration-ms=[Minimum trace duration in milliseconds]:duration:' \ ++ '--query=[Filter by tags or revision, for example tag.region=eu-west]:query:' \ ++ '(--page-all)--limit=[Maximum number of traces to return, 1 to 100]:limit:' \ ++ '(--limit)--page-all[Paginate to fetch all traces]' ++} ++ ++_appsignal_cli__traces__incident() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--number=[Performance incident number]:number:' \ ++ '--action=[Restrict lookup to one action if the incident has several]:action:' \ ++ '--start=[Start time, ISO 8601, defaults to 24 hours ago]:timestamp:' \ ++ '--end=[End time, ISO 8601, defaults to now]:timestamp:' \ ++ '--min-duration-ms=[Minimum trace duration in milliseconds]:duration:' \ ++ '--query=[Filter by tags or revision, for example tag.region=eu-west]:query:' \ ++ '(--page-all)--limit=[Maximum number of traces to return per action, 1 to 100]:limit:' \ ++ '(--limit)--page-all[Paginate to fetch all traces for each action]' ++} ++ ++_appsignal_cli__traces__errors() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--digest=[Exception incident digest]:digest:' \ ++ '--query=[Filter by tags or revision, for example tag.region=eu-west]:query:' \ ++ '(--page-all)--limit=[Maximum number of error traces to return, 1 to 100]:limit:' \ ++ '(--limit)--page-all[Paginate to fetch all error traces]' ++} ++ ++_appsignal_cli__traces__show() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--namespace=[Namespace to search in, for example web, background, graphql]:namespace:' \ ++ '--action=[Action name for the trace, for example UsersController#show]:action:' \ ++ '--trace-id=[Trace ID returned by traces list]:trace id:' \ ++ '--span-id=[Span ID to inspect within the trace]:span id:' \ ++ '--include-sensitive[Include HTTP headers, request parameters, session data and function parameters]' \ ++ '--start=[Start time, ISO 8601, defaults to 24 hours ago]:timestamp:' \ ++ '--end=[End time, ISO 8601, defaults to now]:timestamp:' ++} ++ ++_appsignal_cli__traces__show_error() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--digest=[Exception incident digest]:digest:' \ ++ '--trace-id=[Trace ID returned by traces errors or traces incident]:trace id:' \ ++ '--span-id=[Span ID to inspect within the trace]:span id:' \ ++ '--include-sensitive[Include HTTP headers, request parameters, session data and function parameters]' ++} ++ ++_appsignal_cli__traces__show_incident() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--number=[Performance or exception incident number]:number:' \ ++ '--trace-id=[Trace ID returned by traces incident]:trace id:' \ ++ '--span-id=[Span ID to inspect within the trace]:span id:' \ ++ '--include-sensitive[Include HTTP headers, request parameters, session data and function parameters]' \ ++ '--start=[Start time, ISO 8601, defaults to 24 hours ago]:timestamp:' \ ++ '--end=[End time, ISO 8601, defaults to now]:timestamp:' ++} ++ ++_appsignal_cli__traces() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List performance samples/traces for an action' ++ 'incident:List performance samples/traces for an incident' ++ 'errors:List error traces for an exception digest' ++ 'show:Show a performance sample/trace span tree, or one span with --span-id' ++ 'show-error:Show an error trace span tree, or one span with --span-id' ++ 'show-incident:Show a trace from a performance or exception incident' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'traces command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _appsignal_cli__traces__list && ret=0 ;; ++ incident) _appsignal_cli__traces__incident && ret=0 ;; ++ errors) _appsignal_cli__traces__errors && ret=0 ;; ++ show) _appsignal_cli__traces__show && ret=0 ;; ++ show-error) _appsignal_cli__traces__show_error && ret=0 ;; ++ show-incident) _appsignal_cli__traces__show_incident && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal_cli__dashboards__list() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args ++} ++ ++_appsignal_cli__dashboards__create() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--title=[Dashboard title]:title:' \ ++ '--description=[Dashboard description]:description:' ++} ++ ++_appsignal_cli__dashboards__update() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--id=[ID of the dashboard to update]:dashboard id:' \ ++ '--title=[Dashboard title]:title:' \ ++ '--description=[Dashboard description]:description:' ++} ++ ++_appsignal_cli__dashboards() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List dashboards for an application' ++ 'create:Create a new dashboard' ++ 'update:Update an existing dashboard' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'dashboards command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _appsignal_cli__dashboards__list && ret=0 ;; ++ create) _appsignal_cli__dashboards__create && ret=0 ;; ++ update) _appsignal_cli__dashboards__update && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++# `triggers create` and `triggers update` share this block. Note that --format ++# here is the trigger's own value format, not the global --output alias, so the ++# global flag is offered as -o/--output only. ++_appsignal_cli_trigger_definition_args() { ++ trigger_definition_args=( ++ '--name=[Display name for the trigger, defaults to the metric name]:name:' ++ '--metric-name=[Metric name to monitor]:metric name:' ++ '--kind=[Trigger kind or classification, for example Advanced, Performance, HostCPUUsage]:kind:' ++ '--field=[Metric field to compare]:field:(count counter gauge mean p90 p95)' ++ '--comparison-operator=[Comparison operator]:operator:(> >= < <= == !=)' ++ '--condition-value=[Threshold value to compare against]:value:' ++ '--warmup-duration=[Warmup duration in minutes before opening an alert]:minutes:' ++ '--cooldown-duration=[Cooldown duration in minutes before closing an alert]:minutes:' ++ '--notifier-ids=[Comma-separated notifier IDs to attach to the trigger]:notifier ids:' ++ '*--tag=[Tag filter in key=value form, repeat or use commas]:tag:' ++ '--description=[Optional description shown with the trigger]:description:' ++ '--no-match-is-zero[Treat missing datapoints as 0]' ++ '--dashboard-id=[Dashboard to link the trigger to]:dashboard id:' ++ '--format=[Format for the metric value, for example duration, number, percent]:metric format:' ++ '--format-input=[Input unit for the size format, for example byte, kilobyte, megabyte]:unit:' ++ ) ++} ++ ++_appsignal_cli__triggers__list() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--metric-name=[Filter by metric name]:metric name:' \ ++ '--kind=[Filter by trigger kind]:kind:' \ ++ '*--tag=[Tag filter in key=value form, repeat or use commas]:tag:' ++} ++ ++_appsignal_cli__triggers__create() { ++ local -a app_args trigger_definition_args ++ _appsignal_cli_app_args ++ _appsignal_cli_trigger_definition_args ++ _arguments -s -S $app_args $trigger_definition_args \ ++ '(- *)'{-h,--help}'[Print help]' \ ++ '(-o --output)'{-o,--output}'=[Output format for command results]:format:(human json)' ++} ++ ++_appsignal_cli__triggers__update() { ++ local -a app_args trigger_definition_args ++ _appsignal_cli_app_args ++ _appsignal_cli_trigger_definition_args ++ _arguments -s -S $app_args $trigger_definition_args \ ++ '(- *)'{-h,--help}'[Print help]' \ ++ '(-o --output)'{-o,--output}'=[Output format for command results]:format:(human json)' \ ++ '--id=[ID of the existing trigger to update]:trigger id:' ++} ++ ++_appsignal_cli__triggers__archive() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--id=[ID of the trigger to archive]:trigger id:' ++} ++ ++_appsignal_cli__triggers() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List triggers for an application' ++ 'create:Create a new anomaly detection trigger' ++ 'update:Update a trigger by creating a new version linked to the existing trigger' ++ 'archive:Archive a trigger and close its associated alerts/incidents' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'triggers command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _appsignal_cli__triggers__list && ret=0 ;; ++ create) _appsignal_cli__triggers__create && ret=0 ;; ++ update) _appsignal_cli__triggers__update && ret=0 ;; ++ archive) _appsignal_cli__triggers__archive && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal_cli__feedback() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args \ ++ '(:)'{-m,--message}'=[Feedback text, read from stdin if omitted]:text:' \ ++ '(--no-email)--email=[Contact email for follow-up, saved for next time]:email:' \ ++ '(--email)--no-email[Do not include a contact email, even if one is saved]' \ ++ '(-m --message)*:feedback text:' ++} ++ ++_appsignal_cli__skill__install() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args \ ++ '*--target=[Install target]:target:(opencode codex claude all)' \ ++ '--dir=[Install into this skills root directory instead of the default of the target]:directory:_files -/' \ ++ '--force[Overwrite an existing installed skill]' ++} ++ ++_appsignal_cli__skill__update() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args \ ++ '*--target=[Update target]:target:(opencode codex claude all)' \ ++ '--dir=[Update a skill installed in this skills root directory]:directory:_files -/' ++} ++ ++_appsignal_cli__skill__status() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args \ ++ '*--target=[Status target]:target:(opencode codex claude all)' \ ++ '--dir=[Check a skill installed in this skills root directory]:directory:_files -/' ++} ++ ++_appsignal_cli__skill() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'install:Install the bundled AppSignal skill into an agent skills directory' ++ 'update:Update an installed AppSignal skill to the bundled version' ++ 'status:Show whether installed AppSignal skills are current' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'skill command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ install) _appsignal_cli__skill__install && ret=0 ;; ++ update) _appsignal_cli__skill__update && ret=0 ;; ++ status) _appsignal_cli__skill__status && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal-cli() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'about:Show a more playful overview of the CLI' ++ 'auth:Configure AppSignal authentication' ++ 'apps:List, find, and inspect your AppSignal applications' ++ 'project:Initialize a project-local AppSignal config' ++ 'incidents:List and inspect incidents' ++ 'logs:Stream, search, and inspect application logs' ++ 'traces:Fetch and inspect performance samples/traces' ++ 'dashboards:Create and update dashboards' ++ 'triggers:List and manage anomaly detection triggers' ++ 'feedback:Send feedback about appsignal-cli to AppSignal' ++ 'skill:Install the bundled AppSignal LLM skill' ++ 'help:Print the help of the given subcommands' ++ ) ++ ++ _arguments -C \ ++ '(- *)'{-h,--help}'[Print help]' \ ++ '(- *)'{-V,--version}'[Print version]' \ ++ '(-o --output --format)'{-o,--output,--format}'=[Output format for command results]:format:(human json)' \ ++ '1: :->cmd' \ ++ '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'appsignal-cli command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ about) _appsignal_cli__about && ret=0 ;; ++ auth) _appsignal_cli__auth && ret=0 ;; ++ apps) _appsignal_cli__apps && ret=0 ;; ++ project) _appsignal_cli__project && ret=0 ;; ++ incidents) _appsignal_cli__incidents && ret=0 ;; ++ logs) _appsignal_cli__logs && ret=0 ;; ++ # `samples` and `sample` are aliases of `traces` in the CLI itself. ++ traces|samples|sample) _appsignal_cli__traces && ret=0 ;; ++ dashboards) _appsignal_cli__dashboards && ret=0 ;; ++ triggers) _appsignal_cli__triggers && ret=0 ;; ++ feedback) _appsignal_cli__feedback && ret=0 ;; ++ skill) _appsignal_cli__skill && ret=0 ;; ++ help) _describe -t commands 'appsignal-cli command' commands && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal-cli "$@" +diff --git a/plugins/appsignal-cli/appsignal-cli.plugin.zsh b/plugins/appsignal-cli/appsignal-cli.plugin.zsh +new file mode 100644 +index 00000000..14420059 +--- /dev/null ++++ b/plugins/appsignal-cli/appsignal-cli.plugin.zsh +@@ -0,0 +1,108 @@ ++# AppSignal CLI: completion, aliases and guard rails. ++# https://docs.appsignal.com/cli ++ ++if (( ! $+commands[appsignal-cli] )); then ++ return ++fi ++ ++# Does this invocation need confirming? Sets REPLY to the reason. ++# ++# The command path is collected from the leading bare words. Only the global ++# flags may precede a subcommand, so the first other flag ends the path: that ++# way an option value such as `--app "My App"` is never mistaken for one. ++function _appsignal_cli_is_destructive() { ++ zstyle -T ':omz:plugins:appsignal-cli' confirm-destructive || return 1 ++ ++ # Nobody to answer: CI and pipelines are unaffected. ++ [[ -t 0 ]] || return 1 ++ ++ local -a args=("$@") path numbers ++ local arg state="" ++ integer i=1 n=$# path_done=0 ++ ++ while (( i <= n )); do ++ arg="$args[i]" ++ case "$arg" in ++ --) break ;; ++ --state=*) state="${arg#--state=}"; path_done=1 ;; ++ --state) state="$args[i+1]"; (( i++ )); path_done=1 ;; ++ --number=*) numbers+=(${(s:,:)${arg#--number=}}); path_done=1 ;; ++ # --number takes one or more values, comma-separated or repeated. ++ --number) ++ path_done=1 ++ while (( i < n )) && [[ "$args[i+1]" != -* ]]; do ++ (( i++ )) ++ numbers+=(${(s:,:)args[i]}) ++ done ++ ;; ++ # The output flag is global, so it can appear before the subcommand. ++ -o|--output|--format) (( i++ )) ;; ++ -o*|--output=*|--format=*) ;; ++ -*) path_done=1 ;; ++ *) (( path_done )) || path+=("$arg") ;; ++ esac ++ (( i++ )) ++ done ++ ++ case "${(j: :)path[1,3]}" in ++ "logs metrics delete") ++ REPLY="deleting a log-derived metric cannot be undone." ++ return 0 ++ ;; ++ "logs triggers delete") ++ REPLY="deleting a log-based trigger cannot be undone." ++ return 0 ++ ;; ++ "triggers archive") ++ REPLY="archiving a trigger also closes its alerts and incidents." ++ return 0 ++ ;; ++ "incidents update") ++ if [[ "${(U)state}" == CLOSED ]] && (( $#numbers > 1 )); then ++ REPLY="this closes $#numbers incidents at once." ++ return 0 ++ fi ++ ;; ++ esac ++ ++ return 1 ++} ++ ++# Adds a confirmation prompt before irreversible operations. Everything else ++# passes straight through, so `logs tail` keeps streaming and pipes stay clean. ++function appsignal-cli() { ++ local REPLY ++ if _appsignal_cli_is_destructive "$@"; then ++ print -u2 -- "appsignal-cli: $REPLY" ++ if ! read -q "?Continue? [y/N] "; then ++ print -u2 -- "" ++ return 130 ++ fi ++ print -u2 -- "" ++ fi ++ ++ command appsignal-cli "$@" ++} ++ ++# Complete the aliases like the commands they stand in for. ++if (( $+functions[compdef] )); then ++ _aslog() { ++ words=(appsignal-cli logs tail ${words[2,-1]}) ++ (( CURRENT += 2 )) ++ _appsignal-cli ++ } ++ ++ _asinc() { ++ words=(appsignal-cli incidents list ${words[2,-1]}) ++ (( CURRENT += 2 )) ++ _appsignal-cli ++ } ++ ++ compdef _appsignal-cli asig ++ compdef _aslog aslog ++ compdef _asinc asinc ++fi ++ ++alias asig='appsignal-cli' ++alias aslog='appsignal-cli logs tail' ++alias asinc='appsignal-cli incidents list' diff --git a/tasks/ohmyzsh__ohmyzsh-14038/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14038/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14038/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14038/task.toml b/tasks/ohmyzsh__ohmyzsh-14038/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f56fbb1ff98a2ffc860c636ffab9d6e242af4bc3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14038/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14038" +description = "feat(appsignal-cli): add plugin for AppSignal" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "b842e5e63e90918356b947b3090ceeec549f48b9" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14038" +source_access = "auto" +built_at = "2026-11-16T16:09:56.950336+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5aa2fa556e9b536b1fd084b6aeddd67ed54fb5755a860d7323e1cfc26b4eca33" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-14T19:41:36Z" +diff_format = "unified" +context_files = [ + "plugins/appsignal-cli/README.md", + "plugins/appsignal-cli/_appsignal-cli", + "plugins/appsignal-cli/appsignal-cli.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 1310 +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.971377+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:07681fd024a2aac0457a01555824e7e9f19a80cec6b330c339ba0449521b4d0a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14038/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14038/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14038/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14038/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14038/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ef8422cf819ceea4b94c3a2fc565394c6aaf1145 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14038/tests/instruction.md @@ -0,0 +1,50 @@ +# Issue + +**Title:** feat(appsignal-cli): add plugin for AppSignal + +## Description + +Adds a plugin for the [AppSignal CLI](https://docs.appsignal.com/cli) (`appsignal-cli`), the Rust binary AppSignal released this year for querying incidents, logs and traces from the terminal. + +It ships no completion generator of its own: there is no `appsignal-cli completions` command, it does not depend on `clap_complete`, and it has no machine-readable command dump. So `_appsignal-cli` is written from its command definitions and checked in, the way `plugins/cdk`, `plugins/terraform` and `plugins/shopify` already do. It targets AppSignal CLI 2.1.x. + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- **Completion** for all 11 topics and their subcommands, with the CLI's own descriptions at every level, and their flags and allowed values: incident states and severities, sort orders, log severities, trigger fields and comparison operators, output formats, skill targets. `samples` and `sample` complete like `traces`, as they do in the CLI itself. +- **`--org` completes offline** from the `org` key of the project's `.appsignal.toml`, found by walking up to the git root the way the CLI resolves it, and of the global config. +- **`--app`, `--app-id` and `--environment` complete from the account**, via `appsignal-cli apps list --output json`, showing each app's name and environment next to its ID. Off by default behind `zstyle ':omz:plugins:appsignal-cli' dynamic-app-completion yes`, because it needs authentication and makes a network call on Tab. Results are cached for five minutes. Parsed in zsh, so there is no dependency on `jq`. +- **Three aliases**: `asig` for the CLI itself, `aslog` for `logs tail` and `asinc` for `incidents list`. Those two are the commands people run repeatedly during an incident, and both complete like the command they stand in for, so `aslog --` offers the flags of `logs tail`. +- **A confirmation prompt** before four operations the CLI performs without asking: `logs metrics delete`, `logs triggers delete`, `triggers archive` (which also closes the trigger's alerts and incidents), and `incidents update --state CLOSED` when it names more than one incident, since that flag takes a comma-separated list. Skipped when stdin is not a terminal, so scripts and CI are unaffected, and disabled entirely with `zstyle ':omz:plugins:appsignal-cli' confirm-destructive no`. + +## Screenshot + +image + + +## Other comments: + +The plugin deliberately does **not** claim the bare `appsignal` name. The AppSignal Ruby gem installs its own `appsignal` command (`install`, `diagnose`, `demo`), which is what people run inside their apps; shadowing it would break those projects. Only `appsignal-cli` is wrapped and completed. + +**Testing.** The command surface was checked against the installed binary's `--help` tree across 52 command paths, so every flag the CLI reports is present in the completion. The destructive-command detection has a 17-case table covering the global `--output` flag appearing before the subcommand, `--number=7,8`, `--number 4 5 6`, single-incident closes that should stay quiet, and an app literally named `delete`. The dynamic completion helpers were run against a real account (37 apps), including the cache path. + +**AI disclosure.** The plugin was written with Claude Code, driven and reviewed by me. Two bugs it caught during testing are worth naming, since the same shapes exist elsewhere in the repo: the CLI pretty-prints its JSON, so the split-on-`{` parsing used in `plugins/shopify` returns only partial results until the payload is flattened first; and `_describe` takes the *name* of an array, not its values. + +🤖 Co-authored with Claude Code + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b842e5e63e90`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14038/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14038/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..fc82542e447c7d85037f361e2c5330360c79a2a8 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14038/tests/oracle.patch @@ -0,0 +1,1328 @@ +diff --git a/plugins/appsignal-cli/README.md b/plugins/appsignal-cli/README.md +new file mode 100644 +index 00000000..16b6587d +--- /dev/null ++++ b/plugins/appsignal-cli/README.md +@@ -0,0 +1,122 @@ ++# AppSignal CLI plugin ++ ++This plugin adds aliases, guard rails and completion for the ++[AppSignal CLI](https://docs.appsignal.com/cli). ++ ++To use it, add `appsignal-cli` to the plugins array in your zshrc file: ++ ++```zsh ++plugins=(... appsignal-cli) ++``` ++ ++## Requirements ++ ++[AppSignal CLI](https://docs.appsignal.com/cli) 2.1 or newer, installed and on ++your `PATH`. The plugin does nothing if it is not: ++ ++```zsh ++brew install appsignal/appsignal-cli/appsignal-cli ++# or ++curl -sSL https://github.com/appsignal/appsignal-cli/releases/latest/download/install.sh | sudo sh ++``` ++ ++Most commands need `appsignal-cli auth login` first. ++ ++## Aliases ++ ++| Alias | Command | Description | ++| :------ | :----------------------------- | :--------------------------------- | ++| `asig` | `appsignal-cli` | The AppSignal CLI itself | ++| `aslog` | `appsignal-cli logs tail` | Stream log lines as they arrive | ++| `asinc` | `appsignal-cli incidents list` | List incidents for an application | ++ ++`aslog` and `asinc` complete like the commands they stand in for, so ++`aslog --` offers the flags of `appsignal-cli logs tail`. ++ ++## Functions ++ ++| Function | Description | ++| :-------------- | :----------------------------------------------------------------- | ++| `appsignal-cli` | Wraps the CLI to confirm before irreversible commands. See Settings | ++ ++## Completion ++ ++Every command completes with a description of what it does, at every level, and ++so do their flags and allowed values: incident states and severities, sort ++orders, log severities, trigger fields and comparison operators, output formats ++and skill targets. `samples` and `sample` complete like `traces`, as they do in ++the CLI itself. ++ ++`--org` completes offline from the `org` key of your project's ++`.appsignal.toml` and of the global config. ++ ++The AppSignal CLI ships no completion generator of its own, so `_appsignal-cli` ++is written from its command definitions and kept in this repository. It targets ++AppSignal CLI 2.1.x. ++ ++## Settings ++ ++Set these with `zstyle` in your zshrc, before Oh My Zsh is sourced. ++ ++### Confirming destructive commands ++ ++```zsh ++zstyle ':omz:plugins:appsignal-cli' confirm-destructive no ++``` ++ ++By default the plugin asks for confirmation before four operations that the CLI ++itself performs without a prompt: ++ ++- `appsignal-cli logs metrics delete` ++- `appsignal-cli logs triggers delete` ++- `appsignal-cli triggers archive`, which also closes the trigger's alerts and ++ incidents ++- `appsignal-cli incidents update --state CLOSED` when it names more than one ++ incident, since that flag accepts a comma-separated list ++ ++Nothing else is intercepted, and the prompt is skipped when stdin is not a ++terminal, so scripts, pipelines and CI are unaffected. Set the style to `no` to ++turn the prompt off entirely, or run `command appsignal-cli` for a single ++invocation. ++ ++### Completing applications ++ ++```zsh ++zstyle ':omz:plugins:appsignal-cli' dynamic-app-completion yes ++``` ++ ++Off by default. When enabled, `--app`, `--app-id` and `--environment` are ++completed from `appsignal-cli apps list --output json`, showing each ++application's name and environment next to its ID instead of making you copy ++IDs by hand. It is opt-in because it runs the CLI and makes a network call when ++you press Tab, and because it needs you to be authenticated. Results ++are cached for five minutes. ++ ++### Disabling the aliases ++ ++This works for every Oh My Zsh plugin: ++ ++```zsh ++zstyle ':omz:plugins:appsignal-cli' aliases no ++``` ++ ++## Caveats ++ ++- `appsignal-cli` and the AppSignal Ruby gem's `appsignal` command are different ++ tools. The gem's command installs and diagnoses the agent inside your app; ++ this one queries your data. The plugin deliberately leaves `appsignal` alone, ++ so it keeps working in projects that use the gem. ++- `appsignal-cli` is a shell function here. Run `command appsignal-cli` to reach ++ the binary directly. ++- Most commands need exactly one of `--app-id` or `--app`. `--environment` only ++ narrows `--app`; it does nothing next to `--app-id`. ++- `appsignal-cli project init` writes `.appsignal.toml`, and `auth login` then ++ stores OAuth tokens in it. Do not commit that file. ++- `incidents delete-note`, `auth logout` and the `--clear-*` flags of ++ `logs metrics update` and `logs triggers update` are destructive too, but are ++ not prompted for: each affects a single note, login or field. ++- `triggers create` and `triggers update` have their own `--format`, for the ++ format of the metric value. Everywhere else `--format` is a synonym for ++ `--output`. ++- The CLI sends usage telemetry by default. `APPSIGNAL_CLI_TELEMETRY=0` turns it ++ off, and `APPSIGNAL_CLI_DEBUG=1` shows internal errors. +diff --git a/plugins/appsignal-cli/_appsignal-cli b/plugins/appsignal-cli/_appsignal-cli +new file mode 100644 +index 00000000..138570d8 +--- /dev/null ++++ b/plugins/appsignal-cli/_appsignal-cli +@@ -0,0 +1,1080 @@ ++#compdef appsignal-cli ++ ++# Completion for the AppSignal CLI. https://docs.appsignal.com/cli ++# ++# Targets AppSignal CLI 2.1.x. The CLI has no `completions` command, no ++# clap_complete and no machine-readable command dump, so this is written from ++# its command definitions and kept here. Nothing runs the CLI at completion ++# time unless app completion is enabled below. ++ ++# Organization slugs from the TOML config. Offline, always enabled. ++# The CLI reads .appsignal.toml from the current directory upwards, stopping at ++# the git root, and falls back to the global config. ++_appsignal_cli_orgs() { ++ setopt localoptions extendedglob ++ local -a orgs files ++ local dir file line ++ # (#b) backreferences set $match, which would otherwise be left global. ++ local MATCH MBEGIN MEND ++ local -a match mbegin mend ++ ++ dir="$PWD" ++ while [[ -n "$dir" && "$dir" != "/" ]]; do ++ files+=("$dir/.appsignal.toml") ++ [[ -e "$dir/.git" ]] && break ++ dir="${dir:h}" ++ done ++ files+=("${XDG_CONFIG_HOME:-$HOME/.config}/appsignal/config.toml") ++ files+=("$HOME/Library/Application Support/appsignal/config.toml") ++ ++ for file in $files; do ++ [[ -r "$file" ]] || continue ++ for line in ${(f)"$(< $file)"}; do ++ [[ $line == (#b)[[:space:]]#org[[:space:]]#=[[:space:]]#\"([^\"]##)\"* ]] && orgs+=("$match[1]") ++ done ++ done ++ ++ orgs=(${(u)orgs}) ++ (( $#orgs )) || return 1 ++ _describe -t orgs 'organization' orgs ++} ++ ++# One tab-separated record per app, in $apps. Off by default: needs ++# `appsignal-cli auth login` and makes a network call on TAB. Enable with: ++# zstyle ':omz:plugins:appsignal-cli' dynamic-app-completion yes ++_appsignal_cli_app_cache() { ++ zstyle -t ':omz:plugins:appsignal-cli' dynamic-app-completion || return 1 ++ ++ local cache_file="${ZSH_CACHE_DIR:-$HOME/.cache}/appsignal-cli-apps" ++ local -a fresh ++ local json split entry id name environment ++ # $match and friends are set by =~ and would otherwise be left global. ++ local MATCH MBEGIN MEND ++ local -a match mbegin mend ++ local nl=$'\n' tab=$'\t' ++ ++ # Reuse the cached list for five minutes. ++ fresh=(${cache_file}(Nms-300)) ++ if (( $#fresh )); then ++ apps=("${(@f)$(< "$cache_file")}") ++ (( $#apps )) ++ return ++ fi ++ ++ json="$(command appsignal-cli apps list --output json 2>/dev/null)" || return 1 ++ # The CLI pretty-prints its JSON, so flatten it first, then take one chunk ++ # per object. Done in zsh so there is no dependency on jq. ++ json="${json//$nl/ }" ++ split="${json//\{/$nl}" ++ for entry in ${(f)split}; do ++ id="" name="" environment="" ++ [[ $entry =~ '"id":[[:space:]]*"([^"]*)"' ]] && id=$match[1] ++ [[ $entry =~ '"name":[[:space:]]*"([^"]*)"' ]] && name=$match[1] ++ [[ $entry =~ '"environment":[[:space:]]*"([^"]*)"' ]] && environment=$match[1] ++ [[ -n $id && -n $name ]] || continue ++ apps+=("${id}${tab}${name}${tab}${environment}") ++ done ++ ++ (( $#apps )) || return 1 ++ print -rl -- $apps > "$cache_file" 2>/dev/null ++} ++ ++# Application names. ++_appsignal_cli_apps() { ++ local -a apps names ++ local entry name ++ _appsignal_cli_app_cache || return 1 ++ for entry in $apps; do ++ name="${${(@ps:\t:)entry}[2]}" ++ names+=("${name//:/\\:}") ++ done ++ names=(${(u)names}) ++ _describe -t apps 'application' names ++} ++ ++# Application IDs, described by name and environment. ++_appsignal_cli_app_ids() { ++ local -a apps ids ++ local entry id name environment ++ _appsignal_cli_app_cache || return 1 ++ for entry in $apps; do ++ id="${${(@ps:\t:)entry}[1]}" ++ name="${${(@ps:\t:)entry}[2]}" ++ environment="${${(@ps:\t:)entry}[3]}" ++ ids+=("${id}:${name//:/ }${environment:+ (${environment})}") ++ done ++ _describe -t app-ids 'application' ids ++} ++ ++# Environments seen across the account's apps. ++_appsignal_cli_environments() { ++ local -a apps environments ++ local entry environment ++ _appsignal_cli_app_cache || return 1 ++ for entry in $apps; do ++ environment="${${(@ps:\t:)entry}[3]}" ++ [[ -n $environment ]] && environments+=("${environment//:/\\:}") ++ done ++ (( $#environments )) || return 1 ++ environments=(${(u)environments}) ++ _describe -t environments 'environment' environments ++} ++ ++# Log severity levels, as a comma-separated list. ++_appsignal_cli_severities() { ++ _values -s , 'severity' UNKNOWN TRACE DEBUG INFO NOTICE WARN ERROR CRITICAL ALERT FATAL ++} ++ ++# The global flags, and the app reference group carried by most data commands. ++# Filled into caller-local arrays so the specs are written once, not forty times. ++_appsignal_cli_base_args() { ++ base_args=( ++ '(- *)'{-h,--help}'[Print help]' ++ '(-o --output --format)'{-o,--output,--format}'=[Output format for command results]:format:(human json)' ++ ) ++} ++ ++_appsignal_cli_app_args() { ++ app_args=( ++ '--app-id=[Application ID, an alternative to --app plus --environment]:app id:_appsignal_cli_app_ids' ++ '--app=[Application name, used with optional --environment to find the app]:app:_appsignal_cli_apps' ++ '--environment=[Environment filter, for example production]:environment:_appsignal_cli_environments' ++ '--org=[Organization slug, uses the saved default if omitted]:org:_appsignal_cli_orgs' ++ ) ++} ++ ++_appsignal_cli__about() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args ++} ++ ++_appsignal_cli__auth__login() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args \ ++ '--endpoint=[Override the AppSignal base URL]:url:_urls' \ ++ '--rest-endpoint=[Override the AppSignal REST API base URL]:url:_urls' \ ++ '--oauth-client-id=[Override the OAuth client ID used during login]:client id:' \ ++ '--org=[Set the default organization slug during login]:org:_appsignal_cli_orgs' ++} ++ ++_appsignal_cli__auth__logout() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args ++} ++ ++_appsignal_cli__auth__status() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args ++} ++ ++_appsignal_cli__auth() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'login:Authenticate with AppSignal via OAuth' ++ 'logout:Remove stored credentials' ++ 'status:Show the current authentication status' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'auth command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ login) _appsignal_cli__auth__login && ret=0 ;; ++ logout) _appsignal_cli__auth__logout && ret=0 ;; ++ status) _appsignal_cli__auth__status && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal_cli__apps__list() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args ++} ++ ++_appsignal_cli__apps__info() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args \ ++ '--app-id=[The application ID]:app id:_appsignal_cli_app_ids' ++} ++ ++_appsignal_cli__apps__find() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args \ ++ '--name=[Application name, case-insensitive]:name:_appsignal_cli_apps' \ ++ '--environment=[Environment filter, for example production]:environment:_appsignal_cli_environments' \ ++ '--org=[Organization slug, uses the saved default if omitted]:org:_appsignal_cli_orgs' ++} ++ ++_appsignal_cli__apps__set_org() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args \ ++ '--org=[Organization slug]:org:_appsignal_cli_orgs' ++} ++ ++_appsignal_cli__apps__show_org() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args ++} ++ ++_appsignal_cli__apps__resources__any() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args ++} ++ ++_appsignal_cli__apps__resources() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'all:Show all supported app resources' ++ 'users:Show app users' ++ 'notifiers:Show app notifiers' ++ 'namespaces:Show app namespaces' ++ 'dashboards:Show app dashboards' ++ 'deploy-markers:Show recent deploy markers' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'apps resources command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ all|users|notifiers|namespaces|dashboards|deploy-markers) ++ _appsignal_cli__apps__resources__any && ret=0 ++ ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal_cli__apps() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List all applications for the organization attached to the current OAuth token' ++ 'info:Show details for a specific application by ID' ++ 'find:Find an application by name and optional environment' ++ 'set-org:Set the default organization slug' ++ 'show-org:Show the current default organization' ++ 'resources:Show resources for an app' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'apps command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _appsignal_cli__apps__list && ret=0 ;; ++ info) _appsignal_cli__apps__info && ret=0 ;; ++ find) _appsignal_cli__apps__find && ret=0 ;; ++ set-org) _appsignal_cli__apps__set_org && ret=0 ;; ++ show-org) _appsignal_cli__apps__show_org && ret=0 ;; ++ resources) _appsignal_cli__apps__resources && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal_cli__project__init() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args \ ++ '--endpoint=[Override the AppSignal base URL]:url:_urls' \ ++ '--rest-endpoint=[Override the AppSignal REST API base URL]:url:_urls' \ ++ '--oauth-client-id=[Override the OAuth client ID for this project]:client id:' \ ++ '--org=[Set the default organization slug for this project]:org:_appsignal_cli_orgs' ++} ++ ++_appsignal_cli__project() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'init:Create or update the project-local .appsignal.toml' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'project command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ init) _appsignal_cli__project__init && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++# Shared by every `incidents list*` command. ++_appsignal_cli_incident_list_args() { ++ incident_list_args=( ++ '--limit=[Maximum number of incidents to return]:limit:' ++ '--offset=[Offset for pagination]:offset:' ++ '--state=[Filter by state]:state:(OPEN CLOSED WIP)' ++ '--order=[Sort order, LAST for most recent activity or ID for creation order]:order:(LAST ID)' ++ ) ++} ++ ++_appsignal_cli__incidents__list() { ++ local -a base_args app_args incident_list_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _appsignal_cli_incident_list_args ++ _arguments -s -S $base_args $app_args $incident_list_args \ ++ '--namespaces=[Filter by namespaces, comma-separated, for example web,background]:namespaces:' \ ++ '--action=[Filter by action name, for example UsersController#show]:action:' ++} ++ ++_appsignal_cli__incidents__list_exceptions() { ++ local -a base_args app_args incident_list_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _appsignal_cli_incident_list_args ++ _arguments -s -S $base_args $app_args $incident_list_args \ ++ '--namespaces=[Filter by namespaces, comma-separated, for example web,background]:namespaces:' \ ++ '--action=[Filter by action name, for example UsersController#show]:action:' \ ++ '--query=[Search query to filter exception incidents by name or message]:query:' ++} ++ ++_appsignal_cli__incidents__list_performance() { ++ local -a base_args app_args incident_list_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _appsignal_cli_incident_list_args ++ _arguments -s -S $base_args $app_args $incident_list_args \ ++ '--namespaces=[Filter by namespaces, comma-separated, for example web,background]:namespaces:' \ ++ '--action=[Filter by action name, for example UsersController#show]:action:' \ ++ '--query=[Search query to filter performance incidents by action name]:query:' ++} ++ ++_appsignal_cli__incidents__list_anomalies() { ++ local -a base_args app_args incident_list_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _appsignal_cli_incident_list_args ++ _arguments -s -S $base_args $app_args $incident_list_args ++} ++ ++_appsignal_cli__incidents__show() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--number=[Incident number]:number:' ++} ++ ++_appsignal_cli__incidents__update() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '*--number=[Incident number, repeat or pass a comma-separated list for bulk state changes]:number:' \ ++ '--state=[New state]:state:(OPEN CLOSED WIP)' \ ++ '--severity=[New severity]:severity:(UNTRIAGED CRITICAL HIGH LOW NONE INFORMATIONAL)' \ ++ '--notification-frequency=[How often to notify about this incident]:frequency:(ALWAYS NEVER FIRST_IN_DEPLOY FIRST_AFTER_CLOSE NTH_IN_HOUR NTH_IN_DAY)' \ ++ '--notification-threshold=[Threshold for the NTH_IN_HOUR and NTH_IN_DAY frequencies]:threshold:' \ ++ '--assign=[Comma-separated user names or IDs to add as assignees]:assignees:' \ ++ '--assign-me[Assign the incident to the authenticated CLI user]' \ ++ '--unassign=[Comma-separated user names or IDs to remove from assignees]:assignees:' \ ++ '--description=[New description]:description:' ++} ++ ++_appsignal_cli__incidents__add_note() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--number=[Incident number]:number:' \ ++ '--content=[Note content, markdown supported]:content:' ++} ++ ++_appsignal_cli__incidents__list_notes() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--number=[Incident number]:number:' ++} ++ ++_appsignal_cli__incidents__update_note() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--number=[Incident number]:number:' \ ++ '--id=[ID of the note to update]:note id:' \ ++ '--content=[Note content, markdown supported]:content:' ++} ++ ++_appsignal_cli__incidents__delete_note() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--number=[Incident number]:number:' \ ++ '--id=[ID of the note to delete]:note id:' ++} ++ ++_appsignal_cli__incidents() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List incidents for an application (all types)' ++ 'list-exceptions:List exception incidents (with text search support)' ++ 'list-performance:List performance incidents (with text search support)' ++ 'list-anomalies:List anomaly detection incidents' ++ 'show:Show details for a specific incident by number' ++ 'update:Update an incident (state, severity, notification frequency, assignees)' ++ 'add-note:Add a note to an incident' ++ 'list-notes:List notes on an incident, including their IDs' ++ 'update-note:Update one of your notes on an incident' ++ 'delete-note:Delete one of your notes from an incident' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'incidents command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _appsignal_cli__incidents__list && ret=0 ;; ++ list-exceptions) _appsignal_cli__incidents__list_exceptions && ret=0 ;; ++ list-performance) _appsignal_cli__incidents__list_performance && ret=0 ;; ++ list-anomalies) _appsignal_cli__incidents__list_anomalies && ret=0 ;; ++ show) _appsignal_cli__incidents__show && ret=0 ;; ++ update) _appsignal_cli__incidents__update && ret=0 ;; ++ add-note) _appsignal_cli__incidents__add_note && ret=0 ;; ++ list-notes) _appsignal_cli__incidents__list_notes && ret=0 ;; ++ update-note) _appsignal_cli__incidents__update_note && ret=0 ;; ++ delete-note) _appsignal_cli__incidents__delete_note && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++# Shared by `logs tail` and `logs search`. ++_appsignal_cli_log_filter_args() { ++ log_filter_args=( ++ '--query=[Log query filter, supports field filters and free text]:query:' ++ '--severities=[Comma-separated severity levels, for example ERROR,CRITICAL]:severities:_appsignal_cli_severities' ++ '--source-ids=[Comma-separated source IDs to filter by]:source ids:' ++ '--view=[Log view name or ID, applies the saved filters of the view as defaults]:view:' ++ ) ++} ++ ++_appsignal_cli__logs__tail() { ++ local -a base_args app_args log_filter_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _appsignal_cli_log_filter_args ++ _arguments -s -S $base_args $app_args $log_filter_args ++} ++ ++_appsignal_cli__logs__search() { ++ local -a base_args app_args log_filter_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _appsignal_cli_log_filter_args ++ _arguments -s -S $base_args $app_args $log_filter_args \ ++ '--start=[Start time, ISO 8601]:timestamp:' \ ++ '--end=[End time, ISO 8601]:timestamp:' \ ++ '(--page-all)--limit=[Maximum number of log lines to return, at most 100]:limit:' \ ++ '(--page-all)--order=[Sort order, ASC for oldest first or DESC for newest first]:order:(ASC DESC)' \ ++ '(--limit --order)--page-all[Paginate to fetch all results, requires --start]' ++} ++ ++_appsignal_cli__logs__views() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args ++} ++ ++_appsignal_cli__logs__sources() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args ++} ++ ++_appsignal_cli__logs__metrics__list() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args ++} ++ ++_appsignal_cli__logs__metrics__create() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--name=[Metric configuration name]:name:' \ ++ '--query=[Query expression to match against log lines]:query:' \ ++ '*--source-id=[Scope the metric to a source ID, repeat to add more]:source id:' \ ++ '*--metric=[Metric definition in key=value form, for example name=log.error_count,type=counter]:metric:' ++} ++ ++_appsignal_cli__logs__metrics__update() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--id=[ID of the metric to update]:metric id:' \ ++ '--name=[Metric configuration name]:name:' \ ++ '--query=[Query expression to match against log lines]:query:' \ ++ '(--clear-sources)*--source-id=[Scope the metric to a source ID, repeat to add more]:source id:' \ ++ '(--source-id)--clear-sources[Remove every source from the metric]' \ ++ '(--clear-metrics)*--metric=[Metric definition in key=value form]:metric:' \ ++ '(--metric)--clear-metrics[Remove every metric definition]' ++} ++ ++_appsignal_cli__logs__metrics__delete() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--id=[ID of the metric to delete]:metric id:' ++} ++ ++_appsignal_cli__logs__metrics() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List log-derived metrics for an app' ++ 'create:Create a new log-derived metric' ++ 'update:Update a log-derived metric' ++ 'delete:Delete a log-derived metric' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'logs metrics command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _appsignal_cli__logs__metrics__list && ret=0 ;; ++ create) _appsignal_cli__logs__metrics__create && ret=0 ;; ++ update) _appsignal_cli__logs__metrics__update && ret=0 ;; ++ delete) _appsignal_cli__logs__metrics__delete && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal_cli__logs__triggers__list() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args ++} ++ ++_appsignal_cli__logs__triggers__create() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--name=[Trigger name]:name:' \ ++ '--query=[Query expression to match against log lines]:query:' \ ++ '*--source-id=[Scope the trigger to a source ID, repeat to add more]:source id:' \ ++ '--description=[Optional description shown with the trigger]:description:' \ ++ '*--notifier-id=[Notifier to alert, repeat to add more]:notifier id:' \ ++ '*--severity=[Match only this severity, repeat to add more]:severity:(UNKNOWN TRACE DEBUG INFO NOTICE WARN ERROR CRITICAL ALERT FATAL)' ++} ++ ++_appsignal_cli__logs__triggers__update() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--id=[ID of the trigger to update]:trigger id:' \ ++ '--name=[Trigger name]:name:' \ ++ '--query=[Query expression to match against log lines]:query:' \ ++ '(--clear-sources)*--source-id=[Scope the trigger to a source ID, repeat to add more]:source id:' \ ++ '(--source-id)--clear-sources[Remove every source from the trigger]' \ ++ '(--clear-description)--description=[Optional description shown with the trigger]:description:' \ ++ '(--description)--clear-description[Remove the description]' \ ++ '(--clear-notifiers)*--notifier-id=[Notifier to alert, repeat to add more]:notifier id:' \ ++ '(--notifier-id)--clear-notifiers[Remove every notifier from the trigger]' \ ++ '(--clear-severities)*--severity=[Match only this severity, repeat to add more]:severity:(UNKNOWN TRACE DEBUG INFO NOTICE WARN ERROR CRITICAL ALERT FATAL)' \ ++ '(--severity)--clear-severities[Match every severity]' ++} ++ ++_appsignal_cli__logs__triggers__delete() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--id=[ID of the trigger to delete]:trigger id:' ++} ++ ++_appsignal_cli__logs__triggers() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List log-based triggers for an app' ++ 'create:Create a new log-based trigger' ++ 'update:Update an existing log-based trigger' ++ 'delete:Delete a log-based trigger' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'logs triggers command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _appsignal_cli__logs__triggers__list && ret=0 ;; ++ create) _appsignal_cli__logs__triggers__create && ret=0 ;; ++ update) _appsignal_cli__logs__triggers__update && ret=0 ;; ++ delete) _appsignal_cli__logs__triggers__delete && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal_cli__logs() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'tail:Tail (stream) log lines in real time, with optional filters' ++ 'search:Search log lines (one-shot query)' ++ 'views:List saved log views (filter presets) for an app' ++ 'sources:List log sources for an app' ++ 'metrics:Create and manage log-derived metrics' ++ 'triggers:Create and manage log-based triggers' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'logs command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ tail) _appsignal_cli__logs__tail && ret=0 ;; ++ search) _appsignal_cli__logs__search && ret=0 ;; ++ views) _appsignal_cli__logs__views && ret=0 ;; ++ sources) _appsignal_cli__logs__sources && ret=0 ;; ++ metrics) _appsignal_cli__logs__metrics && ret=0 ;; ++ triggers) _appsignal_cli__logs__triggers && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal_cli__traces__list() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--namespace=[Namespace to search in, for example web, background, graphql]:namespace:' \ ++ '--action=[Action name to fetch traces for, for example UsersController#show]:action:' \ ++ '--start=[Start time, ISO 8601, defaults to 24 hours ago]:timestamp:' \ ++ '--end=[End time, ISO 8601, defaults to now]:timestamp:' \ ++ '--min-duration-ms=[Minimum trace duration in milliseconds]:duration:' \ ++ '--query=[Filter by tags or revision, for example tag.region=eu-west]:query:' \ ++ '(--page-all)--limit=[Maximum number of traces to return, 1 to 100]:limit:' \ ++ '(--limit)--page-all[Paginate to fetch all traces]' ++} ++ ++_appsignal_cli__traces__incident() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--number=[Performance incident number]:number:' \ ++ '--action=[Restrict lookup to one action if the incident has several]:action:' \ ++ '--start=[Start time, ISO 8601, defaults to 24 hours ago]:timestamp:' \ ++ '--end=[End time, ISO 8601, defaults to now]:timestamp:' \ ++ '--min-duration-ms=[Minimum trace duration in milliseconds]:duration:' \ ++ '--query=[Filter by tags or revision, for example tag.region=eu-west]:query:' \ ++ '(--page-all)--limit=[Maximum number of traces to return per action, 1 to 100]:limit:' \ ++ '(--limit)--page-all[Paginate to fetch all traces for each action]' ++} ++ ++_appsignal_cli__traces__errors() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--digest=[Exception incident digest]:digest:' \ ++ '--query=[Filter by tags or revision, for example tag.region=eu-west]:query:' \ ++ '(--page-all)--limit=[Maximum number of error traces to return, 1 to 100]:limit:' \ ++ '(--limit)--page-all[Paginate to fetch all error traces]' ++} ++ ++_appsignal_cli__traces__show() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--namespace=[Namespace to search in, for example web, background, graphql]:namespace:' \ ++ '--action=[Action name for the trace, for example UsersController#show]:action:' \ ++ '--trace-id=[Trace ID returned by traces list]:trace id:' \ ++ '--span-id=[Span ID to inspect within the trace]:span id:' \ ++ '--include-sensitive[Include HTTP headers, request parameters, session data and function parameters]' \ ++ '--start=[Start time, ISO 8601, defaults to 24 hours ago]:timestamp:' \ ++ '--end=[End time, ISO 8601, defaults to now]:timestamp:' ++} ++ ++_appsignal_cli__traces__show_error() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--digest=[Exception incident digest]:digest:' \ ++ '--trace-id=[Trace ID returned by traces errors or traces incident]:trace id:' \ ++ '--span-id=[Span ID to inspect within the trace]:span id:' \ ++ '--include-sensitive[Include HTTP headers, request parameters, session data and function parameters]' ++} ++ ++_appsignal_cli__traces__show_incident() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--number=[Performance or exception incident number]:number:' \ ++ '--trace-id=[Trace ID returned by traces incident]:trace id:' \ ++ '--span-id=[Span ID to inspect within the trace]:span id:' \ ++ '--include-sensitive[Include HTTP headers, request parameters, session data and function parameters]' \ ++ '--start=[Start time, ISO 8601, defaults to 24 hours ago]:timestamp:' \ ++ '--end=[End time, ISO 8601, defaults to now]:timestamp:' ++} ++ ++_appsignal_cli__traces() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List performance samples/traces for an action' ++ 'incident:List performance samples/traces for an incident' ++ 'errors:List error traces for an exception digest' ++ 'show:Show a performance sample/trace span tree, or one span with --span-id' ++ 'show-error:Show an error trace span tree, or one span with --span-id' ++ 'show-incident:Show a trace from a performance or exception incident' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'traces command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _appsignal_cli__traces__list && ret=0 ;; ++ incident) _appsignal_cli__traces__incident && ret=0 ;; ++ errors) _appsignal_cli__traces__errors && ret=0 ;; ++ show) _appsignal_cli__traces__show && ret=0 ;; ++ show-error) _appsignal_cli__traces__show_error && ret=0 ;; ++ show-incident) _appsignal_cli__traces__show_incident && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal_cli__dashboards__list() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args ++} ++ ++_appsignal_cli__dashboards__create() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--title=[Dashboard title]:title:' \ ++ '--description=[Dashboard description]:description:' ++} ++ ++_appsignal_cli__dashboards__update() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--id=[ID of the dashboard to update]:dashboard id:' \ ++ '--title=[Dashboard title]:title:' \ ++ '--description=[Dashboard description]:description:' ++} ++ ++_appsignal_cli__dashboards() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List dashboards for an application' ++ 'create:Create a new dashboard' ++ 'update:Update an existing dashboard' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'dashboards command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _appsignal_cli__dashboards__list && ret=0 ;; ++ create) _appsignal_cli__dashboards__create && ret=0 ;; ++ update) _appsignal_cli__dashboards__update && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++# `triggers create` and `triggers update` share this block. Note that --format ++# here is the trigger's own value format, not the global --output alias, so the ++# global flag is offered as -o/--output only. ++_appsignal_cli_trigger_definition_args() { ++ trigger_definition_args=( ++ '--name=[Display name for the trigger, defaults to the metric name]:name:' ++ '--metric-name=[Metric name to monitor]:metric name:' ++ '--kind=[Trigger kind or classification, for example Advanced, Performance, HostCPUUsage]:kind:' ++ '--field=[Metric field to compare]:field:(count counter gauge mean p90 p95)' ++ '--comparison-operator=[Comparison operator]:operator:(> >= < <= == !=)' ++ '--condition-value=[Threshold value to compare against]:value:' ++ '--warmup-duration=[Warmup duration in minutes before opening an alert]:minutes:' ++ '--cooldown-duration=[Cooldown duration in minutes before closing an alert]:minutes:' ++ '--notifier-ids=[Comma-separated notifier IDs to attach to the trigger]:notifier ids:' ++ '*--tag=[Tag filter in key=value form, repeat or use commas]:tag:' ++ '--description=[Optional description shown with the trigger]:description:' ++ '--no-match-is-zero[Treat missing datapoints as 0]' ++ '--dashboard-id=[Dashboard to link the trigger to]:dashboard id:' ++ '--format=[Format for the metric value, for example duration, number, percent]:metric format:' ++ '--format-input=[Input unit for the size format, for example byte, kilobyte, megabyte]:unit:' ++ ) ++} ++ ++_appsignal_cli__triggers__list() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--metric-name=[Filter by metric name]:metric name:' \ ++ '--kind=[Filter by trigger kind]:kind:' \ ++ '*--tag=[Tag filter in key=value form, repeat or use commas]:tag:' ++} ++ ++_appsignal_cli__triggers__create() { ++ local -a app_args trigger_definition_args ++ _appsignal_cli_app_args ++ _appsignal_cli_trigger_definition_args ++ _arguments -s -S $app_args $trigger_definition_args \ ++ '(- *)'{-h,--help}'[Print help]' \ ++ '(-o --output)'{-o,--output}'=[Output format for command results]:format:(human json)' ++} ++ ++_appsignal_cli__triggers__update() { ++ local -a app_args trigger_definition_args ++ _appsignal_cli_app_args ++ _appsignal_cli_trigger_definition_args ++ _arguments -s -S $app_args $trigger_definition_args \ ++ '(- *)'{-h,--help}'[Print help]' \ ++ '(-o --output)'{-o,--output}'=[Output format for command results]:format:(human json)' \ ++ '--id=[ID of the existing trigger to update]:trigger id:' ++} ++ ++_appsignal_cli__triggers__archive() { ++ local -a base_args app_args ++ _appsignal_cli_base_args ++ _appsignal_cli_app_args ++ _arguments -s -S $base_args $app_args \ ++ '--id=[ID of the trigger to archive]:trigger id:' ++} ++ ++_appsignal_cli__triggers() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'list:List triggers for an application' ++ 'create:Create a new anomaly detection trigger' ++ 'update:Update a trigger by creating a new version linked to the existing trigger' ++ 'archive:Archive a trigger and close its associated alerts/incidents' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'triggers command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ list) _appsignal_cli__triggers__list && ret=0 ;; ++ create) _appsignal_cli__triggers__create && ret=0 ;; ++ update) _appsignal_cli__triggers__update && ret=0 ;; ++ archive) _appsignal_cli__triggers__archive && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal_cli__feedback() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args \ ++ '(:)'{-m,--message}'=[Feedback text, read from stdin if omitted]:text:' \ ++ '(--no-email)--email=[Contact email for follow-up, saved for next time]:email:' \ ++ '(--email)--no-email[Do not include a contact email, even if one is saved]' \ ++ '(-m --message)*:feedback text:' ++} ++ ++_appsignal_cli__skill__install() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args \ ++ '*--target=[Install target]:target:(opencode codex claude all)' \ ++ '--dir=[Install into this skills root directory instead of the default of the target]:directory:_files -/' \ ++ '--force[Overwrite an existing installed skill]' ++} ++ ++_appsignal_cli__skill__update() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args \ ++ '*--target=[Update target]:target:(opencode codex claude all)' \ ++ '--dir=[Update a skill installed in this skills root directory]:directory:_files -/' ++} ++ ++_appsignal_cli__skill__status() { ++ local -a base_args ++ _appsignal_cli_base_args ++ _arguments -s -S $base_args \ ++ '*--target=[Status target]:target:(opencode codex claude all)' \ ++ '--dir=[Check a skill installed in this skills root directory]:directory:_files -/' ++} ++ ++_appsignal_cli__skill() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'install:Install the bundled AppSignal skill into an agent skills directory' ++ 'update:Update an installed AppSignal skill to the bundled version' ++ 'status:Show whether installed AppSignal skills are current' ++ ) ++ ++ _arguments -C '1: :->cmd' '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'skill command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ install) _appsignal_cli__skill__install && ret=0 ;; ++ update) _appsignal_cli__skill__update && ret=0 ;; ++ status) _appsignal_cli__skill__status && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal-cli() { ++ local curcontext="$curcontext" state line ret=1 ++ local -a commands ++ commands=( ++ 'about:Show a more playful overview of the CLI' ++ 'auth:Configure AppSignal authentication' ++ 'apps:List, find, and inspect your AppSignal applications' ++ 'project:Initialize a project-local AppSignal config' ++ 'incidents:List and inspect incidents' ++ 'logs:Stream, search, and inspect application logs' ++ 'traces:Fetch and inspect performance samples/traces' ++ 'dashboards:Create and update dashboards' ++ 'triggers:List and manage anomaly detection triggers' ++ 'feedback:Send feedback about appsignal-cli to AppSignal' ++ 'skill:Install the bundled AppSignal LLM skill' ++ 'help:Print the help of the given subcommands' ++ ) ++ ++ _arguments -C \ ++ '(- *)'{-h,--help}'[Print help]' \ ++ '(- *)'{-V,--version}'[Print version]' \ ++ '(-o --output --format)'{-o,--output,--format}'=[Output format for command results]:format:(human json)' \ ++ '1: :->cmd' \ ++ '*:: :->args' && ret=0 ++ ++ case $state in ++ cmd) ++ _describe -t commands 'appsignal-cli command' commands && ret=0 ++ ;; ++ args) ++ case $words[1] in ++ about) _appsignal_cli__about && ret=0 ;; ++ auth) _appsignal_cli__auth && ret=0 ;; ++ apps) _appsignal_cli__apps && ret=0 ;; ++ project) _appsignal_cli__project && ret=0 ;; ++ incidents) _appsignal_cli__incidents && ret=0 ;; ++ logs) _appsignal_cli__logs && ret=0 ;; ++ # `samples` and `sample` are aliases of `traces` in the CLI itself. ++ traces|samples|sample) _appsignal_cli__traces && ret=0 ;; ++ dashboards) _appsignal_cli__dashboards && ret=0 ;; ++ triggers) _appsignal_cli__triggers && ret=0 ;; ++ feedback) _appsignal_cli__feedback && ret=0 ;; ++ skill) _appsignal_cli__skill && ret=0 ;; ++ help) _describe -t commands 'appsignal-cli command' commands && ret=0 ;; ++ *) _files && ret=0 ;; ++ esac ++ ;; ++ esac ++ ++ return ret ++} ++ ++_appsignal-cli "$@" +diff --git a/plugins/appsignal-cli/appsignal-cli.plugin.zsh b/plugins/appsignal-cli/appsignal-cli.plugin.zsh +new file mode 100644 +index 00000000..14420059 +--- /dev/null ++++ b/plugins/appsignal-cli/appsignal-cli.plugin.zsh +@@ -0,0 +1,108 @@ ++# AppSignal CLI: completion, aliases and guard rails. ++# https://docs.appsignal.com/cli ++ ++if (( ! $+commands[appsignal-cli] )); then ++ return ++fi ++ ++# Does this invocation need confirming? Sets REPLY to the reason. ++# ++# The command path is collected from the leading bare words. Only the global ++# flags may precede a subcommand, so the first other flag ends the path: that ++# way an option value such as `--app "My App"` is never mistaken for one. ++function _appsignal_cli_is_destructive() { ++ zstyle -T ':omz:plugins:appsignal-cli' confirm-destructive || return 1 ++ ++ # Nobody to answer: CI and pipelines are unaffected. ++ [[ -t 0 ]] || return 1 ++ ++ local -a args=("$@") path numbers ++ local arg state="" ++ integer i=1 n=$# path_done=0 ++ ++ while (( i <= n )); do ++ arg="$args[i]" ++ case "$arg" in ++ --) break ;; ++ --state=*) state="${arg#--state=}"; path_done=1 ;; ++ --state) state="$args[i+1]"; (( i++ )); path_done=1 ;; ++ --number=*) numbers+=(${(s:,:)${arg#--number=}}); path_done=1 ;; ++ # --number takes one or more values, comma-separated or repeated. ++ --number) ++ path_done=1 ++ while (( i < n )) && [[ "$args[i+1]" != -* ]]; do ++ (( i++ )) ++ numbers+=(${(s:,:)args[i]}) ++ done ++ ;; ++ # The output flag is global, so it can appear before the subcommand. ++ -o|--output|--format) (( i++ )) ;; ++ -o*|--output=*|--format=*) ;; ++ -*) path_done=1 ;; ++ *) (( path_done )) || path+=("$arg") ;; ++ esac ++ (( i++ )) ++ done ++ ++ case "${(j: :)path[1,3]}" in ++ "logs metrics delete") ++ REPLY="deleting a log-derived metric cannot be undone." ++ return 0 ++ ;; ++ "logs triggers delete") ++ REPLY="deleting a log-based trigger cannot be undone." ++ return 0 ++ ;; ++ "triggers archive") ++ REPLY="archiving a trigger also closes its alerts and incidents." ++ return 0 ++ ;; ++ "incidents update") ++ if [[ "${(U)state}" == CLOSED ]] && (( $#numbers > 1 )); then ++ REPLY="this closes $#numbers incidents at once." ++ return 0 ++ fi ++ ;; ++ esac ++ ++ return 1 ++} ++ ++# Adds a confirmation prompt before irreversible operations. Everything else ++# passes straight through, so `logs tail` keeps streaming and pipes stay clean. ++function appsignal-cli() { ++ local REPLY ++ if _appsignal_cli_is_destructive "$@"; then ++ print -u2 -- "appsignal-cli: $REPLY" ++ if ! read -q "?Continue? [y/N] "; then ++ print -u2 -- "" ++ return 130 ++ fi ++ print -u2 -- "" ++ fi ++ ++ command appsignal-cli "$@" ++} ++ ++# Complete the aliases like the commands they stand in for. ++if (( $+functions[compdef] )); then ++ _aslog() { ++ words=(appsignal-cli logs tail ${words[2,-1]}) ++ (( CURRENT += 2 )) ++ _appsignal-cli ++ } ++ ++ _asinc() { ++ words=(appsignal-cli incidents list ${words[2,-1]}) ++ (( CURRENT += 2 )) ++ _appsignal-cli ++ } ++ ++ compdef _appsignal-cli asig ++ compdef _aslog aslog ++ compdef _asinc asinc ++fi ++ ++alias asig='appsignal-cli' ++alias aslog='appsignal-cli logs tail' ++alias asinc='appsignal-cli incidents list' diff --git a/tasks/ohmyzsh__ohmyzsh-14038/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14038/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..f785c90a43208802e5e92e352194b139a75dd404 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14038/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b842e5e63e90918356b947b3090ceeec549f48b9 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14038/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14038/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14038/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14042/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14042/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..852f80232204a863242d17fcaf4a36af927432b9 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14042/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 593e8ed6c8b4686654e1ff059d1e8e345082c848 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 593e8ed6c8b4686654e1ff059d1e8e345082c848 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 593e8ed6c8b4686654e1ff059d1e8e345082c848 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14042/instruction.md b/tasks/ohmyzsh__ohmyzsh-14042/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8fe9a695ac262153c72da176690c085aea836c5e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14042/instruction.md @@ -0,0 +1,44 @@ +# Issue + +**Title:** fix(agnoster): respect conda changeps1 and escape env name + +## Description + +Picks up the good parts of #7067 (@John-P, 2018), which sat long enough that a different conda implementation shipped first in #13160. . + +`prompt_virtualenv` currently shows the conda segment whenever `CONDA_DEFAULT_ENV` is set. Three problems come out of that: + +**1. The env name shows up twice.** conda's `changeps1` is on by default, so conda already prepends `(myenv) ` to the prompt. Agnoster then adds its own `🐍 myenv` next to it. #7067 guarded against this with `CONDA_PROMPT_MODIFIER` and we didn't carry that over. + +**2. Envs activated by path print the whole path.** `conda activate /opt/conda/envs/myenv` sets `CONDA_DEFAULT_ENV` to that full path, so the segment becomes `🐍 /opt/conda/envs/myenv`. + +**3. A `%` in the env name breaks prompt rendering.** The neighbouring virtualenv line already escapes this; the conda line doesn't: + +```console +$ zsh -f -c 'CONDA_DEFAULT_ENV="my%env"; print -P "${CONDA_DEFAULT_ENV}"' +my0nv +``` + +All three are fixed by making the conda branch behave like the virtualenv branch directly below it. + +### Behavior change worth noting + +Users running conda on default settings will stop seeing the `🐍` segment, because conda is already displaying the env itself. That is the duplication this removes, and it matches how `VIRTUAL_ENV_DISABLE_PROMPT` already gates the virtualenv segment — but it is a visible change for people who didn't opt in, so flagging it explicitly. + +### Testing + +``` +1. conda active, changeps1 off -> [seg |🐍 myenv|] +2. conda active, changeps1 on -> (nothing) +3. env given as a full path -> [seg |🐍 myenv|] +4. env name with a percent sign -> [seg |🐍 my%env|] +5. no conda at all -> (nothing) +``` + +`zsh -n themes/agnoster.zsh-theme` passes. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `593e8ed6c8b4`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14042/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14042/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..bca0c73ed3ae2f35b9834d6c7f6fb831ddd52583 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14042/solution/patch.diff @@ -0,0 +1,18 @@ +diff --git a/themes/agnoster.zsh-theme b/themes/agnoster.zsh-theme +index 63452378..6b6c202a 100644 +--- a/themes/agnoster.zsh-theme ++++ b/themes/agnoster.zsh-theme +@@ -314,8 +314,11 @@ prompt_dir() { + + # Virtualenv: current working virtualenv + prompt_virtualenv() { +- if [ -n "$CONDA_DEFAULT_ENV" ]; then +- prompt_segment magenta $CURRENT_FG "🐍 $CONDA_DEFAULT_ENV" ++ # Skip the conda segment when conda is already showing the environment itself, ++ # i.e. when changeps1 is left on. This mirrors how VIRTUAL_ENV_DISABLE_PROMPT ++ # is handled below, and stops the name appearing twice in the prompt. ++ if [[ -n "$CONDA_DEFAULT_ENV" && -z "$CONDA_PROMPT_MODIFIER" ]]; then ++ prompt_segment magenta $CURRENT_FG "🐍 ${CONDA_DEFAULT_ENV:t:gs/%/%%}" + fi + if [[ -n "$VIRTUAL_ENV" && -n "$VIRTUAL_ENV_DISABLE_PROMPT" ]]; then + prompt_segment "$AGNOSTER_VENV_BG" "$AGNOSTER_VENV_FG" "(${VIRTUAL_ENV:t:gs/%/%%})" diff --git a/tasks/ohmyzsh__ohmyzsh-14042/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14042/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14042/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14042/task.toml b/tasks/ohmyzsh__ohmyzsh-14042/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6db28d5db3ddd7bc79c234f2b9c5f0b54147b9dc --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14042/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14042" +description = "fix(agnoster): respect conda changeps1 and escape env name" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "593e8ed6c8b4686654e1ff059d1e8e345082c848" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14042" +source_access = "auto" +built_at = "2026-11-16T16:09:56.971059+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ea62e0665ea5f96b35d5cca42bb9c29ff9f56e51f20057407abba43bdbedf11d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-10T11:49:39Z" +diff_format = "unified" +context_files = [ + "themes/agnoster.zsh-theme", +] +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.971955+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6eb5e8a9e578c1874a7b5fac41fbb656272ae5171f8eacc15f009f30c7cf74db" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14042/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14042/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14042/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14042/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14042/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8fe9a695ac262153c72da176690c085aea836c5e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14042/tests/instruction.md @@ -0,0 +1,44 @@ +# Issue + +**Title:** fix(agnoster): respect conda changeps1 and escape env name + +## Description + +Picks up the good parts of #7067 (@John-P, 2018), which sat long enough that a different conda implementation shipped first in #13160. . + +`prompt_virtualenv` currently shows the conda segment whenever `CONDA_DEFAULT_ENV` is set. Three problems come out of that: + +**1. The env name shows up twice.** conda's `changeps1` is on by default, so conda already prepends `(myenv) ` to the prompt. Agnoster then adds its own `🐍 myenv` next to it. #7067 guarded against this with `CONDA_PROMPT_MODIFIER` and we didn't carry that over. + +**2. Envs activated by path print the whole path.** `conda activate /opt/conda/envs/myenv` sets `CONDA_DEFAULT_ENV` to that full path, so the segment becomes `🐍 /opt/conda/envs/myenv`. + +**3. A `%` in the env name breaks prompt rendering.** The neighbouring virtualenv line already escapes this; the conda line doesn't: + +```console +$ zsh -f -c 'CONDA_DEFAULT_ENV="my%env"; print -P "${CONDA_DEFAULT_ENV}"' +my0nv +``` + +All three are fixed by making the conda branch behave like the virtualenv branch directly below it. + +### Behavior change worth noting + +Users running conda on default settings will stop seeing the `🐍` segment, because conda is already displaying the env itself. That is the duplication this removes, and it matches how `VIRTUAL_ENV_DISABLE_PROMPT` already gates the virtualenv segment — but it is a visible change for people who didn't opt in, so flagging it explicitly. + +### Testing + +``` +1. conda active, changeps1 off -> [seg |🐍 myenv|] +2. conda active, changeps1 on -> (nothing) +3. env given as a full path -> [seg |🐍 myenv|] +4. env name with a percent sign -> [seg |🐍 my%env|] +5. no conda at all -> (nothing) +``` + +`zsh -n themes/agnoster.zsh-theme` passes. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `593e8ed6c8b4`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14042/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14042/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..bca0c73ed3ae2f35b9834d6c7f6fb831ddd52583 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14042/tests/oracle.patch @@ -0,0 +1,18 @@ +diff --git a/themes/agnoster.zsh-theme b/themes/agnoster.zsh-theme +index 63452378..6b6c202a 100644 +--- a/themes/agnoster.zsh-theme ++++ b/themes/agnoster.zsh-theme +@@ -314,8 +314,11 @@ prompt_dir() { + + # Virtualenv: current working virtualenv + prompt_virtualenv() { +- if [ -n "$CONDA_DEFAULT_ENV" ]; then +- prompt_segment magenta $CURRENT_FG "🐍 $CONDA_DEFAULT_ENV" ++ # Skip the conda segment when conda is already showing the environment itself, ++ # i.e. when changeps1 is left on. This mirrors how VIRTUAL_ENV_DISABLE_PROMPT ++ # is handled below, and stops the name appearing twice in the prompt. ++ if [[ -n "$CONDA_DEFAULT_ENV" && -z "$CONDA_PROMPT_MODIFIER" ]]; then ++ prompt_segment magenta $CURRENT_FG "🐍 ${CONDA_DEFAULT_ENV:t:gs/%/%%}" + fi + if [[ -n "$VIRTUAL_ENV" && -n "$VIRTUAL_ENV_DISABLE_PROMPT" ]]; then + prompt_segment "$AGNOSTER_VENV_BG" "$AGNOSTER_VENV_FG" "(${VIRTUAL_ENV:t:gs/%/%%})" diff --git a/tasks/ohmyzsh__ohmyzsh-14042/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14042/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3cf2a0ac94b18cab9e0a9dae9c7f606a19bebe87 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14042/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 593e8ed6c8b4686654e1ff059d1e8e345082c848 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14042/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14042/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14042/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14049/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14049/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..66a7cd489c7d78a355db7b0d040cfa8aa196a677 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14049/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 87d4d40418438037e6e7576946cffa755d9b7fdf 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 87d4d40418438037e6e7576946cffa755d9b7fdf \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 87d4d40418438037e6e7576946cffa755d9b7fdf \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14049/instruction.md b/tasks/ohmyzsh__ohmyzsh-14049/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0ace3ebcba4a29ba7d471cfa86d0a14d0c874a6d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14049/instruction.md @@ -0,0 +1,50 @@ +# Issue + +**Title:** fix(ssh-agent): add honor-existing to reuse a running agent + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. (No new aliases.) + +## Changes: + +. + +`_start_agent` sources `$HOME/.ssh/environment-$SHORT_HOST` before anything ever reads an inherited `SSH_AUTH_SOCK`, so an agent the session already provides — a desktop keyring, `gpg-agent`, KeePassXC, or one forwarded over SSH — gets overwritten and a second agent is started. Until now the only way to defer to an existing agent was to set `agent-forwarding yes`, which both people on that issue pointed out is a different feature being borrowed for the job. + +- Add an opt-in `honor-existing` style. When set, the plugin probes the inherited `SSH_AUTH_SOCK` and reuses that agent if it answers, only starting its own when there is nothing there. +- Move the socket probe into a small `_is_agent_running` helper shared with the existing cached-agent path. +- Document the new style in the plugin README. + +## Other comments: + +**Default behaviour is unchanged.** The new style is off unless you set it. + +Tested on zsh 5.9 by sourcing the plugin under `zsh -f` with `SSH_AUTH_SOCK` pointed at a real listening socket (created with `zsocket -l`) and a stale cache file on disk, with `ssh-agent` stubbed so no real agent was ever started: + +| | master | this PR | +|---|---|---| +| style unset | starts its own agent, discards the inherited socket | same | +| `honor-existing yes` | starts its own agent, discards the inherited socket | keeps the inherited agent | + +Also ran `zsh -n` on the plugin. + +One incidental fix: `zsocket` leaves the connection it opens in `$REPLY`, and the existing code never closed it, so master leaks a file descriptor on every shell start where the cached agent is live. The shared helper closes it. + +AI disclosure: written with Claude Code, reviewed and tested by me. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `87d4d4041843`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14049/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14049/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..43285fcda2cdb7f3f04d1e04a85b1ddf4043a2eb --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14049/solution/patch.diff @@ -0,0 +1,66 @@ +diff --git a/plugins/ssh-agent/README.md b/plugins/ssh-agent/README.md +index 0afa80cc..04caa46e 100644 +--- a/plugins/ssh-agent/README.md ++++ b/plugins/ssh-agent/README.md +@@ -21,6 +21,18 @@ To enable **agent forwarding support** add the following to your zshrc file: + zstyle :omz:plugins:ssh-agent agent-forwarding yes + ``` + ++### `honor-existing` ++ ++If your session already provides an ssh-agent — a desktop keyring, `gpg-agent`, ++KeePassXC, or an agent forwarded over SSH — the plugin normally ignores it and ++starts one of its own, which leaves you with two agents. Set this to reuse the ++running agent instead, and only start a new one when `$SSH_AUTH_SOCK` is empty ++or does not answer: ++ ++```zsh ++zstyle :omz:plugins:ssh-agent honor-existing yes ++``` ++ + ### `helper` + + To set an **external helper** to ask for the passwords and possibly store +diff --git a/plugins/ssh-agent/ssh-agent.plugin.zsh b/plugins/ssh-agent/ssh-agent.plugin.zsh +index 4517242e..2a3fa8ef 100644 +--- a/plugins/ssh-agent/ssh-agent.plugin.zsh ++++ b/plugins/ssh-agent/ssh-agent.plugin.zsh +@@ -1,16 +1,28 @@ + # Get the filename to store/lookup the environment from + ssh_env_cache="$HOME/.ssh/environment-$SHORT_HOST" + ++# Test if $SSH_AUTH_SOCK points at a listening agent ++function _is_agent_running() { ++ local REPLY ++ [[ -n "$SSH_AUTH_SOCK" && -S "$SSH_AUTH_SOCK" ]] || return 1 ++ zmodload zsh/net/socket 2>/dev/null || return 1 ++ zsocket "$SSH_AUTH_SOCK" 2>/dev/null || return 1 ++ exec {REPLY}>&- # close the probe connection ++ return 0 ++} ++ + function _start_agent() { ++ # Reuse an agent the session already provides, if enabled ++ if zstyle -t :omz:plugins:ssh-agent honor-existing && _is_agent_running; then ++ return 0 ++ fi ++ + # Check if ssh-agent is already running + if [[ -f "$ssh_env_cache" ]]; then + . "$ssh_env_cache" > /dev/null + + # Test if $SSH_AUTH_SOCK is visible +- zmodload zsh/net/socket +- if [[ -S "$SSH_AUTH_SOCK" ]] && zsocket "$SSH_AUTH_SOCK" 2>/dev/null; then +- return 0 +- fi ++ _is_agent_running && return 0 + fi + + if [[ ! -d "$HOME/.ssh" ]]; then +@@ -124,4 +136,4 @@ if ! zstyle -t :omz:plugins:ssh-agent lazy; then + fi + + unset agent_forwarding ssh_env_cache +-unfunction _start_agent _add_identities ++unfunction _start_agent _add_identities _is_agent_running diff --git a/tasks/ohmyzsh__ohmyzsh-14049/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14049/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14049/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14049/task.toml b/tasks/ohmyzsh__ohmyzsh-14049/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ae593de3867a62c7ac30837774943ee562980b8f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14049/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14049" +description = "fix(ssh-agent): add honor-existing to reuse a running agent" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "87d4d40418438037e6e7576946cffa755d9b7fdf" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14049" +source_access = "auto" +built_at = "2026-11-16T16:09:56.975235+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:fc8e803982e8d915a40ffcb60e39cdc2b82c0dcdb150c534cadf4f671d41f2ef" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-10T11:47:34Z" +diff_format = "unified" +context_files = [ + "plugins/ssh-agent/README.md", + "plugins/ssh-agent/ssh-agent.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 34 +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.972567+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d9a574f08b30637806fca5b19b64d1d6b6b45cc386d23aa12a524763d6a3add4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14049/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14049/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14049/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14049/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14049/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0ace3ebcba4a29ba7d471cfa86d0a14d0c874a6d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14049/tests/instruction.md @@ -0,0 +1,50 @@ +# Issue + +**Title:** fix(ssh-agent): add honor-existing to reuse a running agent + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. (No new aliases.) + +## Changes: + +. + +`_start_agent` sources `$HOME/.ssh/environment-$SHORT_HOST` before anything ever reads an inherited `SSH_AUTH_SOCK`, so an agent the session already provides — a desktop keyring, `gpg-agent`, KeePassXC, or one forwarded over SSH — gets overwritten and a second agent is started. Until now the only way to defer to an existing agent was to set `agent-forwarding yes`, which both people on that issue pointed out is a different feature being borrowed for the job. + +- Add an opt-in `honor-existing` style. When set, the plugin probes the inherited `SSH_AUTH_SOCK` and reuses that agent if it answers, only starting its own when there is nothing there. +- Move the socket probe into a small `_is_agent_running` helper shared with the existing cached-agent path. +- Document the new style in the plugin README. + +## Other comments: + +**Default behaviour is unchanged.** The new style is off unless you set it. + +Tested on zsh 5.9 by sourcing the plugin under `zsh -f` with `SSH_AUTH_SOCK` pointed at a real listening socket (created with `zsocket -l`) and a stale cache file on disk, with `ssh-agent` stubbed so no real agent was ever started: + +| | master | this PR | +|---|---|---| +| style unset | starts its own agent, discards the inherited socket | same | +| `honor-existing yes` | starts its own agent, discards the inherited socket | keeps the inherited agent | + +Also ran `zsh -n` on the plugin. + +One incidental fix: `zsocket` leaves the connection it opens in `$REPLY`, and the existing code never closed it, so master leaks a file descriptor on every shell start where the cached agent is live. The shared helper closes it. + +AI disclosure: written with Claude Code, reviewed and tested by me. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `87d4d4041843`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14049/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14049/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..43285fcda2cdb7f3f04d1e04a85b1ddf4043a2eb --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14049/tests/oracle.patch @@ -0,0 +1,66 @@ +diff --git a/plugins/ssh-agent/README.md b/plugins/ssh-agent/README.md +index 0afa80cc..04caa46e 100644 +--- a/plugins/ssh-agent/README.md ++++ b/plugins/ssh-agent/README.md +@@ -21,6 +21,18 @@ To enable **agent forwarding support** add the following to your zshrc file: + zstyle :omz:plugins:ssh-agent agent-forwarding yes + ``` + ++### `honor-existing` ++ ++If your session already provides an ssh-agent — a desktop keyring, `gpg-agent`, ++KeePassXC, or an agent forwarded over SSH — the plugin normally ignores it and ++starts one of its own, which leaves you with two agents. Set this to reuse the ++running agent instead, and only start a new one when `$SSH_AUTH_SOCK` is empty ++or does not answer: ++ ++```zsh ++zstyle :omz:plugins:ssh-agent honor-existing yes ++``` ++ + ### `helper` + + To set an **external helper** to ask for the passwords and possibly store +diff --git a/plugins/ssh-agent/ssh-agent.plugin.zsh b/plugins/ssh-agent/ssh-agent.plugin.zsh +index 4517242e..2a3fa8ef 100644 +--- a/plugins/ssh-agent/ssh-agent.plugin.zsh ++++ b/plugins/ssh-agent/ssh-agent.plugin.zsh +@@ -1,16 +1,28 @@ + # Get the filename to store/lookup the environment from + ssh_env_cache="$HOME/.ssh/environment-$SHORT_HOST" + ++# Test if $SSH_AUTH_SOCK points at a listening agent ++function _is_agent_running() { ++ local REPLY ++ [[ -n "$SSH_AUTH_SOCK" && -S "$SSH_AUTH_SOCK" ]] || return 1 ++ zmodload zsh/net/socket 2>/dev/null || return 1 ++ zsocket "$SSH_AUTH_SOCK" 2>/dev/null || return 1 ++ exec {REPLY}>&- # close the probe connection ++ return 0 ++} ++ + function _start_agent() { ++ # Reuse an agent the session already provides, if enabled ++ if zstyle -t :omz:plugins:ssh-agent honor-existing && _is_agent_running; then ++ return 0 ++ fi ++ + # Check if ssh-agent is already running + if [[ -f "$ssh_env_cache" ]]; then + . "$ssh_env_cache" > /dev/null + + # Test if $SSH_AUTH_SOCK is visible +- zmodload zsh/net/socket +- if [[ -S "$SSH_AUTH_SOCK" ]] && zsocket "$SSH_AUTH_SOCK" 2>/dev/null; then +- return 0 +- fi ++ _is_agent_running && return 0 + fi + + if [[ ! -d "$HOME/.ssh" ]]; then +@@ -124,4 +136,4 @@ if ! zstyle -t :omz:plugins:ssh-agent lazy; then + fi + + unset agent_forwarding ssh_env_cache +-unfunction _start_agent _add_identities ++unfunction _start_agent _add_identities _is_agent_running diff --git a/tasks/ohmyzsh__ohmyzsh-14049/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14049/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3007348b30edf787046a068dae4d49d323c3585a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14049/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 87d4d40418438037e6e7576946cffa755d9b7fdf > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14049/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14049/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14049/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14050/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14050/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..66a7cd489c7d78a355db7b0d040cfa8aa196a677 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14050/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 87d4d40418438037e6e7576946cffa755d9b7fdf 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 87d4d40418438037e6e7576946cffa755d9b7fdf \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 87d4d40418438037e6e7576946cffa755d9b7fdf \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14050/instruction.md b/tasks/ohmyzsh__ohmyzsh-14050/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8279d9ec02598ed831ca72cee153ab9b21d17b4d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14050/instruction.md @@ -0,0 +1,52 @@ +# Issue + +**Title:** feat(systemd): add `sc-edit-full` + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +. This reapplies @galenguyer's #11217, which had gone stale against master — the change is his, the rebase is mine. + +`systemctl edit` writes a drop-in override under `/etc/systemd/system/.d/`. `systemctl edit --full` copies the whole unit file and edits that instead. They are different operations, and there was no alias for the second one. + +- `sc-edit-full` → `sudo systemctl edit --full` +- `scu-edit-full` → `systemctl --user edit --full` +- One README row, next to the existing `sc-edit` entry. + +### Use case for the new aliases + +`--full` is the standard way to change something the drop-in mechanism cannot express — reordering or clearing an existing directive, or editing `ExecStart` when the unit sets it once. Anyone maintaining units on a Linux box reaches for it regularly, and the plugin already ships the analogous `--now` variants (`sc-enable-now`, `sc-disable-now`, `sc-mask-now`) built exactly this way, so this adds no new pattern. + +Note this **adds** an alias rather than changing `sc-edit`. @carlosala made that call on the issue in 2022: changing the default would be a breaking change for anyone with it in muscle memory. + +## Other comments: + +Tested on zsh 5.9 by sourcing the plugin under `zsh -f` with `sudo` and `systemctl` stubbed, and checking the aliases resolve all the way through: + +``` +sc-edit-full nginx -> sudo systemctl edit --full nginx +scu-edit-full nginx -> systemctl --user edit --full nginx +``` + +Also ran `zsh -n` on the plugin. + +AI disclosure: reapplied and tested with Claude Code. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `87d4d4041843`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14050/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14050/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ddd0532a31616f8046ee1a7d7944c77a4b4e2a74 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14050/solution/patch.diff @@ -0,0 +1,27 @@ +diff --git a/plugins/systemd/README.md b/plugins/systemd/README.md +index 755c649a..1980ae37 100644 +--- a/plugins/systemd/README.md ++++ b/plugins/systemd/README.md +@@ -45,6 +45,7 @@ plugins=(... systemd) + | `sc-set-environment` | `sudo systemctl set-environment` | Set one or more systemd manager environment variables | + | `sc-unset-environment` | `sudo systemctl unset-environment` | Unset one or more systemd manager environment variables | + | `sc-edit` | `sudo systemctl edit` | Edit a drop-in snippet or a whole replacement file with `--full` | ++| `sc-edit-full` | `sudo systemctl edit --full` | Edit the whole unit file instead of a drop-in snippet | + | `sc-enable-now` | `sudo systemctl enable --now` | Enable and start unit(s) | + | `sc-disable-now` | `sudo systemctl disable --now` | Disable and stop unit(s) | + | `sc-mask-now` | `sudo systemctl mask --now` | Mask and stop unit(s) | +diff --git a/plugins/systemd/systemd.plugin.zsh b/plugins/systemd/systemd.plugin.zsh +index 382a57b2..842174df 100644 +--- a/plugins/systemd/systemd.plugin.zsh ++++ b/plugins/systemd/systemd.plugin.zsh +@@ -97,6 +97,10 @@ alias scu-mask-now="scu-mask --now" + alias scu-failed='systemctl --user --failed' + alias sc-failed='systemctl --failed' + ++# --full commands ++alias sc-edit-full="sc-edit --full" ++alias scu-edit-full="scu-edit --full" ++ + function systemd_prompt_info { + local unit + for unit in "$@"; do diff --git a/tasks/ohmyzsh__ohmyzsh-14050/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14050/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14050/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14050/task.toml b/tasks/ohmyzsh__ohmyzsh-14050/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dbad1577c8a3f9c721fa949f40dfa21cffe6b36d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14050/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14050" +description = "feat(systemd): add `sc-edit-full`" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "87d4d40418438037e6e7576946cffa755d9b7fdf" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14050" +source_access = "auto" +built_at = "2026-11-16T16:09:56.982077+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:08267a36e32376c1bf6d68a64a8fc7d86473ea5e3b385577c779068ff37000ee" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-09T15:02:41Z" +diff_format = "unified" +context_files = [ + "plugins/systemd/README.md", + "plugins/systemd/systemd.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.973781+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d9a574f08b30637806fca5b19b64d1d6b6b45cc386d23aa12a524763d6a3add4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14050/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14050/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14050/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14050/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14050/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8279d9ec02598ed831ca72cee153ab9b21d17b4d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14050/tests/instruction.md @@ -0,0 +1,52 @@ +# Issue + +**Title:** feat(systemd): add `sc-edit-full` + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +. This reapplies @galenguyer's #11217, which had gone stale against master — the change is his, the rebase is mine. + +`systemctl edit` writes a drop-in override under `/etc/systemd/system/.d/`. `systemctl edit --full` copies the whole unit file and edits that instead. They are different operations, and there was no alias for the second one. + +- `sc-edit-full` → `sudo systemctl edit --full` +- `scu-edit-full` → `systemctl --user edit --full` +- One README row, next to the existing `sc-edit` entry. + +### Use case for the new aliases + +`--full` is the standard way to change something the drop-in mechanism cannot express — reordering or clearing an existing directive, or editing `ExecStart` when the unit sets it once. Anyone maintaining units on a Linux box reaches for it regularly, and the plugin already ships the analogous `--now` variants (`sc-enable-now`, `sc-disable-now`, `sc-mask-now`) built exactly this way, so this adds no new pattern. + +Note this **adds** an alias rather than changing `sc-edit`. @carlosala made that call on the issue in 2022: changing the default would be a breaking change for anyone with it in muscle memory. + +## Other comments: + +Tested on zsh 5.9 by sourcing the plugin under `zsh -f` with `sudo` and `systemctl` stubbed, and checking the aliases resolve all the way through: + +``` +sc-edit-full nginx -> sudo systemctl edit --full nginx +scu-edit-full nginx -> systemctl --user edit --full nginx +``` + +Also ran `zsh -n` on the plugin. + +AI disclosure: reapplied and tested with Claude Code. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `87d4d4041843`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14050/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14050/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ddd0532a31616f8046ee1a7d7944c77a4b4e2a74 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14050/tests/oracle.patch @@ -0,0 +1,27 @@ +diff --git a/plugins/systemd/README.md b/plugins/systemd/README.md +index 755c649a..1980ae37 100644 +--- a/plugins/systemd/README.md ++++ b/plugins/systemd/README.md +@@ -45,6 +45,7 @@ plugins=(... systemd) + | `sc-set-environment` | `sudo systemctl set-environment` | Set one or more systemd manager environment variables | + | `sc-unset-environment` | `sudo systemctl unset-environment` | Unset one or more systemd manager environment variables | + | `sc-edit` | `sudo systemctl edit` | Edit a drop-in snippet or a whole replacement file with `--full` | ++| `sc-edit-full` | `sudo systemctl edit --full` | Edit the whole unit file instead of a drop-in snippet | + | `sc-enable-now` | `sudo systemctl enable --now` | Enable and start unit(s) | + | `sc-disable-now` | `sudo systemctl disable --now` | Disable and stop unit(s) | + | `sc-mask-now` | `sudo systemctl mask --now` | Mask and stop unit(s) | +diff --git a/plugins/systemd/systemd.plugin.zsh b/plugins/systemd/systemd.plugin.zsh +index 382a57b2..842174df 100644 +--- a/plugins/systemd/systemd.plugin.zsh ++++ b/plugins/systemd/systemd.plugin.zsh +@@ -97,6 +97,10 @@ alias scu-mask-now="scu-mask --now" + alias scu-failed='systemctl --user --failed' + alias sc-failed='systemctl --failed' + ++# --full commands ++alias sc-edit-full="sc-edit --full" ++alias scu-edit-full="scu-edit --full" ++ + function systemd_prompt_info { + local unit + for unit in "$@"; do diff --git a/tasks/ohmyzsh__ohmyzsh-14050/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14050/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3007348b30edf787046a068dae4d49d323c3585a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14050/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 87d4d40418438037e6e7576946cffa755d9b7fdf > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14050/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14050/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14050/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14051/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14051/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..66a7cd489c7d78a355db7b0d040cfa8aa196a677 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14051/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 87d4d40418438037e6e7576946cffa755d9b7fdf 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 87d4d40418438037e6e7576946cffa755d9b7fdf \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 87d4d40418438037e6e7576946cffa755d9b7fdf \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14051/instruction.md b/tasks/ohmyzsh__ohmyzsh-14051/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2783b948aa3aa42f8ef5d04bae1c02c2539860c5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14051/instruction.md @@ -0,0 +1,61 @@ +# Issue + +**Title:** fix(common-aliases): open documents with the platform's opener + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. (No new aliases; five existing ones change target.) + +## Changes: + +. + +The document suffix aliases in `common-aliases` point at Linux/X11 binaries: + +```zsh +alias -s pdf=acroread +alias -s ps=gv +alias -s dvi=xdvi +alias -s chm=xchm +alias -s djvu=djview +``` + +So on macOS, typing `report.pdf` gives `zsh: command not found: acroread`. Adobe also stopped shipping `acroread` for Linux a long time ago, so that one is mostly broken everywhere. + +The reporter suggested `xdg-open`, which would fix Linux and leave macOS broken in the same way. We already have the right tool for this: `open_command` in `lib/functions.zsh` dispatches on `$OSTYPE` — `open` on macOS, `nohup xdg-open` on Linux (with a WSL branch), `cygstart` on Cygwin, `start` on MSYS. It is always loaded, and six other plugins already use it. + +- Five suffix aliases now use `open_command`, following the `_*_fts` loop style used by the browser/editor/image/media aliases just above. +- README table and the surrounding explanation updated. + +## Other comments: + +This changes behaviour for Linux users who actually had `acroread`, `gv`, `xdvi`, `xchm` or `djview` installed: they now get their desktop's default handler instead. That seems right — it is what the rest of the plugin already does via `$BROWSER`, `$EDITOR` and `$XIVIEWER` — but it is a behaviour change, not purely a fix, so worth a second opinion. `common-aliases` is opt-in. + +Tested on zsh 5.9 by sourcing `lib/functions.zsh` and the plugin under `zsh -f` with `open` stubbed to log its arguments: + +``` +/tmp/omz-t.pdf -> open /tmp/omz-t.pdf +/tmp/omz-t.djvu -> open /tmp/omz-t.djvu +``` + +Before the change the same aliases resolved to `acroread` and `djview`. Also confirmed a zsh suffix alias accepts a function as its target, and ran `zsh -n`. + +One pre-existing wart worth knowing about, unchanged here: `open_command` ends in `&>/dev/null`, so if the platform opener is missing the failure is silent rather than a `command not found`. + +AI disclosure: written and tested with Claude Code. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `87d4d4041843`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14051/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14051/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..12104dc74ccb839ab9194b8131fca993eaf250b4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14051/solution/patch.diff @@ -0,0 +1,55 @@ +diff --git a/plugins/common-aliases/README.md b/plugins/common-aliases/README.md +index 79e3d0d0..83d86edf 100644 +--- a/plugins/common-aliases/README.md ++++ b/plugins/common-aliases/README.md +@@ -99,18 +99,21 @@ $ find . -type f 2>/dev/null + ## File extension aliases + + These are special aliases that are triggered when a file name is passed as the command. For example, +-if the pdf file extension is aliased to `acroread` (a popular Linux pdf reader), when running `file.pdf` +-that file will be open with `acroread`. ++if the pdf file extension is aliased to `open_command`, running `file.pdf` opens that file with ++whatever application your system uses for PDFs. + + ### Reading Docs + +-| Alias | Command | Description | +-| ----- | ---------- | ---------------------------------- | +-| pdf | `acroread` | Opens up a document using acroread | +-| ps | `gv` | Opens up a .ps file using gv | +-| dvi | `xdvi` | Opens up a .dvi file using xdvi | +-| chm | `xchm` | Opens up a .chm file using xchm | +-| djvu | `djview` | Opens up a .djvu file using djview | ++These use `open_command`, which picks the right opener for your platform: `open` on macOS, ++`xdg-open` on Linux, `cygstart` on Cygwin. ++ ++| Alias | Command | Description | ++| ----- | -------------- | ----------------------------------------------- | ++| pdf | `open_command` | Opens up a .pdf file in your default viewer | ++| ps | `open_command` | Opens up a .ps file in your default viewer | ++| dvi | `open_command` | Opens up a .dvi file in your default viewer | ++| chm | `open_command` | Opens up a .chm file in your default viewer | ++| djvu | `open_command` | Opens up a .djvu file in your default viewer | + + ### Listing files inside a packed file + +diff --git a/plugins/common-aliases/common-aliases.plugin.zsh b/plugins/common-aliases/common-aliases.plugin.zsh +index 8db4b955..21587eaf 100644 +--- a/plugins/common-aliases/common-aliases.plugin.zsh ++++ b/plugins/common-aliases/common-aliases.plugin.zsh +@@ -71,12 +71,9 @@ if is-at-least 4.2.0; then + _media_fts=(ape avi flv m4a mkv mov mp3 mpeg mpg ogg ogm rm wav webm) + for ft in $_media_fts; do alias -s $ft=mplayer; done + +- #read documents +- alias -s pdf=acroread +- alias -s ps=gv +- alias -s dvi=xdvi +- alias -s chm=xchm +- alias -s djvu=djview ++ # read documents with the platform's default application ++ _doc_fts=(pdf ps dvi chm djvu) ++ for ft in $_doc_fts; do alias -s $ft=open_command; done + + #list what's inside packed file + alias -s zip="unzip -l" diff --git a/tasks/ohmyzsh__ohmyzsh-14051/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14051/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14051/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14051/task.toml b/tasks/ohmyzsh__ohmyzsh-14051/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dd05d8df44eed0bec84613b17777f1882671eaf4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14051/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14051" +description = "fix(common-aliases): open documents with the platform's opener" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "87d4d40418438037e6e7576946cffa755d9b7fdf" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14051" +source_access = "auto" +built_at = "2026-11-16T16:09:56.973184+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6329d47a753731f076422c773e19293bdb0836646f4dd3586fab6964129df037" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-10T11:48:51Z" +diff_format = "unified" +context_files = [ + "plugins/common-aliases/README.md", + "plugins/common-aliases/common-aliases.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 30 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.975789+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d9a574f08b30637806fca5b19b64d1d6b6b45cc386d23aa12a524763d6a3add4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14051/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14051/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14051/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14051/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14051/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2783b948aa3aa42f8ef5d04bae1c02c2539860c5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14051/tests/instruction.md @@ -0,0 +1,61 @@ +# Issue + +**Title:** fix(common-aliases): open documents with the platform's opener + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. (No new aliases; five existing ones change target.) + +## Changes: + +. + +The document suffix aliases in `common-aliases` point at Linux/X11 binaries: + +```zsh +alias -s pdf=acroread +alias -s ps=gv +alias -s dvi=xdvi +alias -s chm=xchm +alias -s djvu=djview +``` + +So on macOS, typing `report.pdf` gives `zsh: command not found: acroread`. Adobe also stopped shipping `acroread` for Linux a long time ago, so that one is mostly broken everywhere. + +The reporter suggested `xdg-open`, which would fix Linux and leave macOS broken in the same way. We already have the right tool for this: `open_command` in `lib/functions.zsh` dispatches on `$OSTYPE` — `open` on macOS, `nohup xdg-open` on Linux (with a WSL branch), `cygstart` on Cygwin, `start` on MSYS. It is always loaded, and six other plugins already use it. + +- Five suffix aliases now use `open_command`, following the `_*_fts` loop style used by the browser/editor/image/media aliases just above. +- README table and the surrounding explanation updated. + +## Other comments: + +This changes behaviour for Linux users who actually had `acroread`, `gv`, `xdvi`, `xchm` or `djview` installed: they now get their desktop's default handler instead. That seems right — it is what the rest of the plugin already does via `$BROWSER`, `$EDITOR` and `$XIVIEWER` — but it is a behaviour change, not purely a fix, so worth a second opinion. `common-aliases` is opt-in. + +Tested on zsh 5.9 by sourcing `lib/functions.zsh` and the plugin under `zsh -f` with `open` stubbed to log its arguments: + +``` +/tmp/omz-t.pdf -> open /tmp/omz-t.pdf +/tmp/omz-t.djvu -> open /tmp/omz-t.djvu +``` + +Before the change the same aliases resolved to `acroread` and `djview`. Also confirmed a zsh suffix alias accepts a function as its target, and ran `zsh -n`. + +One pre-existing wart worth knowing about, unchanged here: `open_command` ends in `&>/dev/null`, so if the platform opener is missing the failure is silent rather than a `command not found`. + +AI disclosure: written and tested with Claude Code. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `87d4d4041843`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14051/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14051/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..12104dc74ccb839ab9194b8131fca993eaf250b4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14051/tests/oracle.patch @@ -0,0 +1,55 @@ +diff --git a/plugins/common-aliases/README.md b/plugins/common-aliases/README.md +index 79e3d0d0..83d86edf 100644 +--- a/plugins/common-aliases/README.md ++++ b/plugins/common-aliases/README.md +@@ -99,18 +99,21 @@ $ find . -type f 2>/dev/null + ## File extension aliases + + These are special aliases that are triggered when a file name is passed as the command. For example, +-if the pdf file extension is aliased to `acroread` (a popular Linux pdf reader), when running `file.pdf` +-that file will be open with `acroread`. ++if the pdf file extension is aliased to `open_command`, running `file.pdf` opens that file with ++whatever application your system uses for PDFs. + + ### Reading Docs + +-| Alias | Command | Description | +-| ----- | ---------- | ---------------------------------- | +-| pdf | `acroread` | Opens up a document using acroread | +-| ps | `gv` | Opens up a .ps file using gv | +-| dvi | `xdvi` | Opens up a .dvi file using xdvi | +-| chm | `xchm` | Opens up a .chm file using xchm | +-| djvu | `djview` | Opens up a .djvu file using djview | ++These use `open_command`, which picks the right opener for your platform: `open` on macOS, ++`xdg-open` on Linux, `cygstart` on Cygwin. ++ ++| Alias | Command | Description | ++| ----- | -------------- | ----------------------------------------------- | ++| pdf | `open_command` | Opens up a .pdf file in your default viewer | ++| ps | `open_command` | Opens up a .ps file in your default viewer | ++| dvi | `open_command` | Opens up a .dvi file in your default viewer | ++| chm | `open_command` | Opens up a .chm file in your default viewer | ++| djvu | `open_command` | Opens up a .djvu file in your default viewer | + + ### Listing files inside a packed file + +diff --git a/plugins/common-aliases/common-aliases.plugin.zsh b/plugins/common-aliases/common-aliases.plugin.zsh +index 8db4b955..21587eaf 100644 +--- a/plugins/common-aliases/common-aliases.plugin.zsh ++++ b/plugins/common-aliases/common-aliases.plugin.zsh +@@ -71,12 +71,9 @@ if is-at-least 4.2.0; then + _media_fts=(ape avi flv m4a mkv mov mp3 mpeg mpg ogg ogm rm wav webm) + for ft in $_media_fts; do alias -s $ft=mplayer; done + +- #read documents +- alias -s pdf=acroread +- alias -s ps=gv +- alias -s dvi=xdvi +- alias -s chm=xchm +- alias -s djvu=djview ++ # read documents with the platform's default application ++ _doc_fts=(pdf ps dvi chm djvu) ++ for ft in $_doc_fts; do alias -s $ft=open_command; done + + #list what's inside packed file + alias -s zip="unzip -l" diff --git a/tasks/ohmyzsh__ohmyzsh-14051/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14051/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3007348b30edf787046a068dae4d49d323c3585a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14051/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 87d4d40418438037e6e7576946cffa755d9b7fdf > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14051/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14051/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14051/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14052/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14052/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..66a7cd489c7d78a355db7b0d040cfa8aa196a677 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14052/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 87d4d40418438037e6e7576946cffa755d9b7fdf 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 87d4d40418438037e6e7576946cffa755d9b7fdf \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 87d4d40418438037e6e7576946cffa755d9b7fdf \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14052/instruction.md b/tasks/ohmyzsh__ohmyzsh-14052/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fc59d64d749bd419ea09ecf0e00c39c8f39033e3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14052/instruction.md @@ -0,0 +1,62 @@ +# Issue + +**Title:** fix(termsupport): set title correctly on terminals with parameterized tsl + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. *(no new aliases)* + +## Changes: + +- `lib/termsupport.zsh`: in the terminfo fallback branch of `title()`, emit `tsl` and `fsl` with `echoti` instead of interpolating them into a `print -Pn` string. + +. + +## Other comments: + +**The bug.** The branch did: + +```zsh +print -Pn "${terminfo[tsl]}$1${terminfo[fsl]}" +``` + +`$1` needs prompt expansion — callers pass things like `%15<..<%~%<<` — but the capability string must not get it. A parameterized `tsl` is then read as prompt escapes. On vt320, `tsl` is `\E[2$~\E[1$}\E[%i%p1%d\``, so `%d` expanded to the working directory and the sequence went out malformed, with the cwd embedded in it. + +**The fix.** `echoti` asks terminfo to do its own parameter substitution, which is what these capabilities expect. Prompt expansion still applies to the title text, and only to that. + +**Testing.** Compared emitted bytes before and after, in `/tmp`, with `zsh -f`: + +``` +TERM=vt320 + before ^[[2$~^[[1$}^[[41/tmp`/tmp^[[0$} + after ^[[2$~^[[1$}^[[1`/tmp^[[0$} + +TERM=ghostty + before ^[]2;/tmp^G + after ^[]2;/tmp^G (unchanged) + +TERM=xterm-256color, TERM=screen + take the earlier case branches; untouched by this change +``` + +Terminals whose `tsl` takes no parameters are byte-identical. `linux` and `xterm-kitty` do not define `tsl`/`fsl` at all and never reach this branch. + +**Credit.** @franrogers diagnosed this in #8519 in January 2020 and is credited with a `Co-Authored-By` trailer. His patch also added an unconditional `echoti dl1`, which is left out here: Ghostty reaches this same branch, and `dl1` would inject `\E[M` into the middle of its OSC sequence. + +**AI assistance.** Found during backlog triage and prepared with Claude Code. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `87d4d4041843`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14052/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14052/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9b3d82ba431b4c5c1324dae6d5ee3ab35e5e5826 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14052/solution/patch.diff @@ -0,0 +1,18 @@ +diff --git a/lib/termsupport.zsh b/lib/termsupport.zsh +index 852a543c..74dc3d25 100644 +--- a/lib/termsupport.zsh ++++ b/lib/termsupport.zsh +@@ -31,7 +31,12 @@ function title { + else + # Try to use terminfo to set the title if the feature is available + if (( ${+terminfo[fsl]} && ${+terminfo[tsl]} )); then +- print -Pn "${terminfo[tsl]}$1${terminfo[fsl]}" ++ # Emit the capabilities with echoti so terminfo does its own parameter ++ # substitution: some terminals (vt320) take a column argument, and ++ # running prompt expansion over the capability string mangles it. ++ echoti tsl 0 ++ print -Pn "$1" ++ echoti fsl + fi + fi + ;; diff --git a/tasks/ohmyzsh__ohmyzsh-14052/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14052/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14052/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14052/task.toml b/tasks/ohmyzsh__ohmyzsh-14052/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c5f52032ff1acffff43bc3e93e285e6875a57226 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14052/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14052" +description = "fix(termsupport): set title correctly on terminals with parameterized tsl" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "87d4d40418438037e6e7576946cffa755d9b7fdf" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14052" +source_access = "auto" +built_at = "2026-11-16T16:09:56.978979+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:08f15358480d7b7c29f133de0c632594baff437093ed905b63dccbb12457348d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-09T15:12:33Z" +diff_format = "unified" +context_files = [ + "lib/termsupport.zsh", +] +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.977330+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d9a574f08b30637806fca5b19b64d1d6b6b45cc386d23aa12a524763d6a3add4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14052/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14052/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14052/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14052/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14052/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fc59d64d749bd419ea09ecf0e00c39c8f39033e3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14052/tests/instruction.md @@ -0,0 +1,62 @@ +# Issue + +**Title:** fix(termsupport): set title correctly on terminals with parameterized tsl + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. *(no new aliases)* + +## Changes: + +- `lib/termsupport.zsh`: in the terminfo fallback branch of `title()`, emit `tsl` and `fsl` with `echoti` instead of interpolating them into a `print -Pn` string. + +. + +## Other comments: + +**The bug.** The branch did: + +```zsh +print -Pn "${terminfo[tsl]}$1${terminfo[fsl]}" +``` + +`$1` needs prompt expansion — callers pass things like `%15<..<%~%<<` — but the capability string must not get it. A parameterized `tsl` is then read as prompt escapes. On vt320, `tsl` is `\E[2$~\E[1$}\E[%i%p1%d\``, so `%d` expanded to the working directory and the sequence went out malformed, with the cwd embedded in it. + +**The fix.** `echoti` asks terminfo to do its own parameter substitution, which is what these capabilities expect. Prompt expansion still applies to the title text, and only to that. + +**Testing.** Compared emitted bytes before and after, in `/tmp`, with `zsh -f`: + +``` +TERM=vt320 + before ^[[2$~^[[1$}^[[41/tmp`/tmp^[[0$} + after ^[[2$~^[[1$}^[[1`/tmp^[[0$} + +TERM=ghostty + before ^[]2;/tmp^G + after ^[]2;/tmp^G (unchanged) + +TERM=xterm-256color, TERM=screen + take the earlier case branches; untouched by this change +``` + +Terminals whose `tsl` takes no parameters are byte-identical. `linux` and `xterm-kitty` do not define `tsl`/`fsl` at all and never reach this branch. + +**Credit.** @franrogers diagnosed this in #8519 in January 2020 and is credited with a `Co-Authored-By` trailer. His patch also added an unconditional `echoti dl1`, which is left out here: Ghostty reaches this same branch, and `dl1` would inject `\E[M` into the middle of its OSC sequence. + +**AI assistance.** Found during backlog triage and prepared with Claude Code. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `87d4d4041843`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14052/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14052/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9b3d82ba431b4c5c1324dae6d5ee3ab35e5e5826 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14052/tests/oracle.patch @@ -0,0 +1,18 @@ +diff --git a/lib/termsupport.zsh b/lib/termsupport.zsh +index 852a543c..74dc3d25 100644 +--- a/lib/termsupport.zsh ++++ b/lib/termsupport.zsh +@@ -31,7 +31,12 @@ function title { + else + # Try to use terminfo to set the title if the feature is available + if (( ${+terminfo[fsl]} && ${+terminfo[tsl]} )); then +- print -Pn "${terminfo[tsl]}$1${terminfo[fsl]}" ++ # Emit the capabilities with echoti so terminfo does its own parameter ++ # substitution: some terminals (vt320) take a column argument, and ++ # running prompt expansion over the capability string mangles it. ++ echoti tsl 0 ++ print -Pn "$1" ++ echoti fsl + fi + fi + ;; diff --git a/tasks/ohmyzsh__ohmyzsh-14052/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14052/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3007348b30edf787046a068dae4d49d323c3585a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14052/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 87d4d40418438037e6e7576946cffa755d9b7fdf > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14052/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14052/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14052/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14053/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14053/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..66a7cd489c7d78a355db7b0d040cfa8aa196a677 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14053/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 87d4d40418438037e6e7576946cffa755d9b7fdf 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 87d4d40418438037e6e7576946cffa755d9b7fdf \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 87d4d40418438037e6e7576946cffa755d9b7fdf \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14053/instruction.md b/tasks/ohmyzsh__ohmyzsh-14053/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e24cba007580f07dd9a357f337dd86b53300aa51 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14053/instruction.md @@ -0,0 +1,76 @@ +# Issue + +**Title:** fix: remove shadowed alias definitions and two related defects + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. (No new aliases; two dead ones removed.) + +## Changes: + +Four small defects found while sweeping the issue backlog. Each is one commit, and **none of them changes what any alias does today.** + +### `fix(suse)` — `zcl` was defined twice, with different meanings + +```zsh +alias zcl='sudo zypper clean' # repositories section — dead +alias zcl='sudo zypper cl' # package locks section — wins +``` + +These are different commands: `zypper clean` empties the package cache, `zypper cl` is `cleanlocks`. The README documented `zcl` **twice**, once as "clean cache" and once as "remove unused locks", so anyone who read the first row and ran `zcl` was removing package locks instead. Present since 2018. + +Removed the dead definition and the README row describing behaviour the plugin does not have. `zcl` still runs `sudo zypper cl`, unchanged — fixing that instead would be a breaking change, so this only makes the docs honest. Worth noting there is now no alias for `zypper clean`; happy to add one if wanted, but that is a separate decision. + +### `fix(rails)` — `sd` was defined twice, one line apart + +`alias sd='ruby script/destroy'` sits directly above `alias sd='ruby script/server --debugger'`. The first has had no effect since the second was added in 2021. Removed the dead line. + +### `fix(safe-paste)` — a `set` line that clobbered `$@` + +```zsh +set zle_bracketed_paste # Explicitly restore this zsh default +``` + +There is no shell option called `zle_bracketed_paste` (`setopt` lists none), and `set` with a bare word assigns positional parameters. Sourcing the plugin replaced `$1` with the literal string `zle_bracketed_paste`: + +``` +before: $1=[alpha] $#=2 +after: $1=[zle_bracketed_paste] $#=1 +``` + +`zle_bracketed_paste` is an array parameter, so the line was not setting that either. Removing it does not change paste behaviour. + +### `fix(aws)` — `aws_profiles` listed `[sso-session ...]` as a profile + +The fallback used when the `aws` binary is missing matched every bracketed header. Against a config with an `[sso-session]` and a `[services]` block: + +``` +before: default, foo, spaced-out, [sso-session my-sso], [services my-services] +after: default, foo, spaced-out +``` + +Real profiles are still found, including ones with irregular spacing after `profile`. + +## Other comments: + +Tested on zsh 5.9. Each plugin passes `zsh -n`, and I checked the two surviving aliases resolve exactly as before (`zcl='sudo zypper cl'`, `sd='ruby script/server --debugger'`), that `$@` survives sourcing safe-paste, and the `aws_profiles` fallback against a synthetic `AWS_CONFIG_FILE` — no real credentials or network involved. + +They are four separate commits with their own scopes, so a rebase merge keeps the changelog entries per-plugin. Happy to split into four PRs if that suits better. + +AI disclosure: found and fixed with Claude Code. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `87d4d4041843`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14053/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14053/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..55d67289164936cbbd9d0b420c3f762f46871ad1 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14053/solution/patch.diff @@ -0,0 +1,61 @@ +diff --git a/plugins/aws/aws.plugin.zsh b/plugins/aws/aws.plugin.zsh +index c78531db..6f3d483b 100644 +--- a/plugins/aws/aws.plugin.zsh ++++ b/plugins/aws/aws.plugin.zsh +@@ -241,7 +241,7 @@ function aws_regions() { + function aws_profiles() { + aws --no-cli-pager configure list-profiles 2> /dev/null && return + [[ -r "${AWS_CONFIG_FILE:-$HOME/.aws/config}" ]] || return 1 +- grep --color=never -Eo '\[.*\]' "${AWS_CONFIG_FILE:-$HOME/.aws/config}" | sed -E 's/^[[:space:]]*\[(profile)?[[:space:]]*([^[:space:]]+)\][[:space:]]*$/\2/g' ++ command grep -Eo '^[[:space:]]*\[[[:space:]]*(profile[[:space:]]+)?[^][:space:]]+[[:space:]]*\]' "${AWS_CONFIG_FILE:-$HOME/.aws/config}" | command sed -E 's/^[[:space:]]*\[[[:space:]]*(profile[[:space:]]+)?([^][:space:]]+)[[:space:]]*\]$/\2/' + } + + function _aws_regions() { +diff --git a/plugins/rails/rails.plugin.zsh b/plugins/rails/rails.plugin.zsh +index a01a2368..24bc9e42 100644 +--- a/plugins/rails/rails.plugin.zsh ++++ b/plugins/rails/rails.plugin.zsh +@@ -139,7 +139,6 @@ function rdsl() { _rails_db_command db:schema:load "$@" } + + # legacy stuff + alias sc='ruby script/console' +-alias sd='ruby script/destroy' + alias sd='ruby script/server --debugger' + alias sg='ruby script/generate' + alias sp='ruby script/plugin' +diff --git a/plugins/safe-paste/safe-paste.plugin.zsh b/plugins/safe-paste/safe-paste.plugin.zsh +index c7079059..36135aa6 100644 +--- a/plugins/safe-paste/safe-paste.plugin.zsh ++++ b/plugins/safe-paste/safe-paste.plugin.zsh +@@ -11,7 +11,6 @@ + # Load bracketed-paste-magic if zsh version is >= 5.1 + autoload -Uz is-at-least + if is-at-least 5.1; then +- set zle_bracketed_paste # Explicitly restore this zsh default + autoload -Uz bracketed-paste-magic + zle -N bracketed-paste bracketed-paste-magic + return ### The rest of this file is NOT executed on zsh version >= 5.1 ### +diff --git a/plugins/suse/README.md b/plugins/suse/README.md +index e1e3aad2..35971698 100644 +--- a/plugins/suse/README.md ++++ b/plugins/suse/README.md +@@ -71,7 +71,6 @@ Related: [#9798](https://github.com/ohmyzsh/ohmyzsh/pull/9798). + | Alias | Commands | Description | + | ----- | ------------------- | ---------------------------------------- | + | zar | `sudo zypper ar` | add a repository | +-| zcl | `sudo zypper clean` | clean cache | + | zlr | `zypper lr` | list repositories | + | zmr | `sudo zypper mr` | modify repositories | + | znr | `sudo zypper nr` | rename repositories (for the alias only) | +diff --git a/plugins/suse/suse.plugin.zsh b/plugins/suse/suse.plugin.zsh +index 56bc6f1c..7407a04d 100644 +--- a/plugins/suse/suse.plugin.zsh ++++ b/plugins/suse/suse.plugin.zsh +@@ -38,7 +38,6 @@ alias zwp='zypper --no-refresh wp' + + #Repositories commands + alias zar='sudo zypper ar' +-alias zcl='sudo zypper clean' + alias zlr='zypper lr' + alias zmr='sudo zypper mr' + alias znr='sudo zypper nr' diff --git a/tasks/ohmyzsh__ohmyzsh-14053/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14053/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14053/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14053/task.toml b/tasks/ohmyzsh__ohmyzsh-14053/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dce055d24484f8c2cfa1bde84f6a3b81076bf5b8 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14053/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14053" +description = "fix: remove shadowed alias definitions and two related defects" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "87d4d40418438037e6e7576946cffa755d9b7fdf" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14053" +source_access = "auto" +built_at = "2026-11-16T16:09:56.967626+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2537c090fbcaeb3aa9a531b3e5c49346d36d4c18ff9d0cfa79046f9a1ce3cb5a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-10T11:54:45Z" +diff_format = "unified" +context_files = [ + "plugins/aws/aws.plugin.zsh", + "plugins/rails/rails.plugin.zsh", + "plugins/safe-paste/safe-paste.plugin.zsh", + "plugins/suse/README.md", + "plugins/suse/suse.plugin.zsh", +] +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.978018+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d9a574f08b30637806fca5b19b64d1d6b6b45cc386d23aa12a524763d6a3add4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14053/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14053/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14053/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14053/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14053/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e24cba007580f07dd9a357f337dd86b53300aa51 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14053/tests/instruction.md @@ -0,0 +1,76 @@ +# Issue + +**Title:** fix: remove shadowed alias definitions and two related defects + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. (No new aliases; two dead ones removed.) + +## Changes: + +Four small defects found while sweeping the issue backlog. Each is one commit, and **none of them changes what any alias does today.** + +### `fix(suse)` — `zcl` was defined twice, with different meanings + +```zsh +alias zcl='sudo zypper clean' # repositories section — dead +alias zcl='sudo zypper cl' # package locks section — wins +``` + +These are different commands: `zypper clean` empties the package cache, `zypper cl` is `cleanlocks`. The README documented `zcl` **twice**, once as "clean cache" and once as "remove unused locks", so anyone who read the first row and ran `zcl` was removing package locks instead. Present since 2018. + +Removed the dead definition and the README row describing behaviour the plugin does not have. `zcl` still runs `sudo zypper cl`, unchanged — fixing that instead would be a breaking change, so this only makes the docs honest. Worth noting there is now no alias for `zypper clean`; happy to add one if wanted, but that is a separate decision. + +### `fix(rails)` — `sd` was defined twice, one line apart + +`alias sd='ruby script/destroy'` sits directly above `alias sd='ruby script/server --debugger'`. The first has had no effect since the second was added in 2021. Removed the dead line. + +### `fix(safe-paste)` — a `set` line that clobbered `$@` + +```zsh +set zle_bracketed_paste # Explicitly restore this zsh default +``` + +There is no shell option called `zle_bracketed_paste` (`setopt` lists none), and `set` with a bare word assigns positional parameters. Sourcing the plugin replaced `$1` with the literal string `zle_bracketed_paste`: + +``` +before: $1=[alpha] $#=2 +after: $1=[zle_bracketed_paste] $#=1 +``` + +`zle_bracketed_paste` is an array parameter, so the line was not setting that either. Removing it does not change paste behaviour. + +### `fix(aws)` — `aws_profiles` listed `[sso-session ...]` as a profile + +The fallback used when the `aws` binary is missing matched every bracketed header. Against a config with an `[sso-session]` and a `[services]` block: + +``` +before: default, foo, spaced-out, [sso-session my-sso], [services my-services] +after: default, foo, spaced-out +``` + +Real profiles are still found, including ones with irregular spacing after `profile`. + +## Other comments: + +Tested on zsh 5.9. Each plugin passes `zsh -n`, and I checked the two surviving aliases resolve exactly as before (`zcl='sudo zypper cl'`, `sd='ruby script/server --debugger'`), that `$@` survives sourcing safe-paste, and the `aws_profiles` fallback against a synthetic `AWS_CONFIG_FILE` — no real credentials or network involved. + +They are four separate commits with their own scopes, so a rebase merge keeps the changelog entries per-plugin. Happy to split into four PRs if that suits better. + +AI disclosure: found and fixed with Claude Code. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `87d4d4041843`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14053/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14053/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..55d67289164936cbbd9d0b420c3f762f46871ad1 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14053/tests/oracle.patch @@ -0,0 +1,61 @@ +diff --git a/plugins/aws/aws.plugin.zsh b/plugins/aws/aws.plugin.zsh +index c78531db..6f3d483b 100644 +--- a/plugins/aws/aws.plugin.zsh ++++ b/plugins/aws/aws.plugin.zsh +@@ -241,7 +241,7 @@ function aws_regions() { + function aws_profiles() { + aws --no-cli-pager configure list-profiles 2> /dev/null && return + [[ -r "${AWS_CONFIG_FILE:-$HOME/.aws/config}" ]] || return 1 +- grep --color=never -Eo '\[.*\]' "${AWS_CONFIG_FILE:-$HOME/.aws/config}" | sed -E 's/^[[:space:]]*\[(profile)?[[:space:]]*([^[:space:]]+)\][[:space:]]*$/\2/g' ++ command grep -Eo '^[[:space:]]*\[[[:space:]]*(profile[[:space:]]+)?[^][:space:]]+[[:space:]]*\]' "${AWS_CONFIG_FILE:-$HOME/.aws/config}" | command sed -E 's/^[[:space:]]*\[[[:space:]]*(profile[[:space:]]+)?([^][:space:]]+)[[:space:]]*\]$/\2/' + } + + function _aws_regions() { +diff --git a/plugins/rails/rails.plugin.zsh b/plugins/rails/rails.plugin.zsh +index a01a2368..24bc9e42 100644 +--- a/plugins/rails/rails.plugin.zsh ++++ b/plugins/rails/rails.plugin.zsh +@@ -139,7 +139,6 @@ function rdsl() { _rails_db_command db:schema:load "$@" } + + # legacy stuff + alias sc='ruby script/console' +-alias sd='ruby script/destroy' + alias sd='ruby script/server --debugger' + alias sg='ruby script/generate' + alias sp='ruby script/plugin' +diff --git a/plugins/safe-paste/safe-paste.plugin.zsh b/plugins/safe-paste/safe-paste.plugin.zsh +index c7079059..36135aa6 100644 +--- a/plugins/safe-paste/safe-paste.plugin.zsh ++++ b/plugins/safe-paste/safe-paste.plugin.zsh +@@ -11,7 +11,6 @@ + # Load bracketed-paste-magic if zsh version is >= 5.1 + autoload -Uz is-at-least + if is-at-least 5.1; then +- set zle_bracketed_paste # Explicitly restore this zsh default + autoload -Uz bracketed-paste-magic + zle -N bracketed-paste bracketed-paste-magic + return ### The rest of this file is NOT executed on zsh version >= 5.1 ### +diff --git a/plugins/suse/README.md b/plugins/suse/README.md +index e1e3aad2..35971698 100644 +--- a/plugins/suse/README.md ++++ b/plugins/suse/README.md +@@ -71,7 +71,6 @@ Related: [#9798](https://github.com/ohmyzsh/ohmyzsh/pull/9798). + | Alias | Commands | Description | + | ----- | ------------------- | ---------------------------------------- | + | zar | `sudo zypper ar` | add a repository | +-| zcl | `sudo zypper clean` | clean cache | + | zlr | `zypper lr` | list repositories | + | zmr | `sudo zypper mr` | modify repositories | + | znr | `sudo zypper nr` | rename repositories (for the alias only) | +diff --git a/plugins/suse/suse.plugin.zsh b/plugins/suse/suse.plugin.zsh +index 56bc6f1c..7407a04d 100644 +--- a/plugins/suse/suse.plugin.zsh ++++ b/plugins/suse/suse.plugin.zsh +@@ -38,7 +38,6 @@ alias zwp='zypper --no-refresh wp' + + #Repositories commands + alias zar='sudo zypper ar' +-alias zcl='sudo zypper clean' + alias zlr='zypper lr' + alias zmr='sudo zypper mr' + alias znr='sudo zypper nr' diff --git a/tasks/ohmyzsh__ohmyzsh-14053/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14053/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3007348b30edf787046a068dae4d49d323c3585a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14053/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 87d4d40418438037e6e7576946cffa755d9b7fdf > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14053/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14053/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14053/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14055/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14055/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..66a7cd489c7d78a355db7b0d040cfa8aa196a677 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14055/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 87d4d40418438037e6e7576946cffa755d9b7fdf 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 87d4d40418438037e6e7576946cffa755d9b7fdf \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 87d4d40418438037e6e7576946cffa755d9b7fdf \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14055/instruction.md b/tasks/ohmyzsh__ohmyzsh-14055/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7c6516a14d85a63fd24a79fd3bb676c7d31540d2 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14055/instruction.md @@ -0,0 +1,54 @@ +# Issue + +**Title:** fix(emacs): drop `--no-wait` when opening a terminal frame + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. (No aliases.) + +## Changes: + +. + +The plugin's `emacs` alias always adds `--no-wait`, so `emacs -nw file` arrives at emacsclient as: + +``` +emacsclient --alternate-editor= --create-frame --no-wait -nw file +``` + +`--no-wait` asks emacsclient to return immediately, which cannot work for a terminal frame — the client has to stay attached to the tty. It exits straight away and nothing opens, so the shell looks like it ignored the command. The plugin's own `te` alias avoids this because it never passes `--no-wait`. + +`emacsclient.sh` already inspects the arguments for `-t`/`--tty`/`-nw` to decide which frames to look for; this reuses that to strip `--no-wait` on those paths. + +## Other comments: + +Tested with `emacsclient` stubbed to log its arguments (no real emacs launched), running the script directly with each argument list: + +| invocation | master | this PR | +| --- | --- | --- | +| `emacs --no-wait -nw file.txt` | `--create-frame --no-wait -nw file.txt` | `--create-frame -nw file.txt` | +| `emacs --no-wait -t file.txt` | `--create-frame --no-wait -t file.txt` | `--create-frame -t file.txt` | +| `emacs --no-wait file.txt` | `--create-frame --no-wait file.txt` | unchanged | +| `emacs -nw file.txt` | `--create-frame -nw file.txt` | unchanged | + +So the GUI path is untouched. Also ran `sh -n` on the script. + +The argument rebuild uses the portable `for arg do shift; …; set -- "$@" "$arg"; done` idiom, since this file is `#!/bin/sh`; I checked it behaves the same under dash, bash and zsh. + +AI disclosure: diagnosed and fixed with Claude Code. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `87d4d4041843`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14055/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14055/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..583be20b20cd5845edc28d401fa1969dd23448e4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14055/solution/patch.diff @@ -0,0 +1,43 @@ +diff --git a/plugins/emacs/emacsclient.sh b/plugins/emacs/emacsclient.sh +index 172c0ae9..208eec71 100755 +--- a/plugins/emacs/emacsclient.sh ++++ b/plugins/emacs/emacsclient.sh +@@ -1,14 +1,33 @@ + #!/bin/sh + + emacsfun() { +- local cmd frames ++ local cmd frames arg tty + + # Build the Emacs Lisp command to check for suitable frames + # See https://www.gnu.org/software/emacs/manual/html_node/elisp/Frames.html#index-framep +- case "$*" in +- *-t*|*--tty*|*-nw*) cmd="(memq 't (mapcar 'framep (frame-list)))" ;; # if != nil, there are tty frames +- *) cmd="(delete 't (mapcar 'framep (frame-list)))" ;; # if != nil, there are graphical terminals (x, w32, ns) +- esac ++ for arg in "$@"; do ++ case "$arg" in ++ -t|--tty|-nw) tty=1; break ;; ++ esac ++ done ++ ++ if [ -n "$tty" ]; then ++ cmd="(memq 't (mapcar 'framep (frame-list)))" # if != nil, there are tty frames ++ else ++ cmd="(delete 't (mapcar 'framep (frame-list)))" # if != nil, there are graphical terminals (x, w32, ns) ++ fi ++ ++ # A tty frame needs the client to stay attached, so drop the --no-wait the ++ # `emacs` alias adds. Otherwise emacsclient returns at once and nothing opens. ++ if [ -n "$tty" ]; then ++ for arg do ++ shift ++ case "$arg" in ++ --no-wait) continue ;; ++ esac ++ set -- "$@" "$arg" ++ done ++ fi + + # Check if there are suitable frames + frames="$(emacsclient -a '' -n -e "$cmd" 2>/dev/null |sed 's/.*\x07//g' )" diff --git a/tasks/ohmyzsh__ohmyzsh-14055/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14055/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14055/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14055/task.toml b/tasks/ohmyzsh__ohmyzsh-14055/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..49e4ac76747ed34d1f4e8513ee66d0021d408312 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14055/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14055" +description = "fix(emacs): drop `--no-wait` when opening a terminal frame" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "87d4d40418438037e6e7576946cffa755d9b7fdf" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14055" +source_access = "auto" +built_at = "2026-11-16T16:09:56.969449+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8554a3ae56d3c1b6bdc1103edbd3ea288583c223be4c485134feb685c2b813ba" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-10T11:51:47Z" +diff_format = "unified" +context_files = [ + "plugins/emacs/emacsclient.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 29 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.978554+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d9a574f08b30637806fca5b19b64d1d6b6b45cc386d23aa12a524763d6a3add4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14055/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14055/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14055/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14055/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14055/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7c6516a14d85a63fd24a79fd3bb676c7d31540d2 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14055/tests/instruction.md @@ -0,0 +1,54 @@ +# Issue + +**Title:** fix(emacs): drop `--no-wait` when opening a terminal frame + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. (No aliases.) + +## Changes: + +. + +The plugin's `emacs` alias always adds `--no-wait`, so `emacs -nw file` arrives at emacsclient as: + +``` +emacsclient --alternate-editor= --create-frame --no-wait -nw file +``` + +`--no-wait` asks emacsclient to return immediately, which cannot work for a terminal frame — the client has to stay attached to the tty. It exits straight away and nothing opens, so the shell looks like it ignored the command. The plugin's own `te` alias avoids this because it never passes `--no-wait`. + +`emacsclient.sh` already inspects the arguments for `-t`/`--tty`/`-nw` to decide which frames to look for; this reuses that to strip `--no-wait` on those paths. + +## Other comments: + +Tested with `emacsclient` stubbed to log its arguments (no real emacs launched), running the script directly with each argument list: + +| invocation | master | this PR | +| --- | --- | --- | +| `emacs --no-wait -nw file.txt` | `--create-frame --no-wait -nw file.txt` | `--create-frame -nw file.txt` | +| `emacs --no-wait -t file.txt` | `--create-frame --no-wait -t file.txt` | `--create-frame -t file.txt` | +| `emacs --no-wait file.txt` | `--create-frame --no-wait file.txt` | unchanged | +| `emacs -nw file.txt` | `--create-frame -nw file.txt` | unchanged | + +So the GUI path is untouched. Also ran `sh -n` on the script. + +The argument rebuild uses the portable `for arg do shift; …; set -- "$@" "$arg"; done` idiom, since this file is `#!/bin/sh`; I checked it behaves the same under dash, bash and zsh. + +AI disclosure: diagnosed and fixed with Claude Code. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `87d4d4041843`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14055/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14055/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..583be20b20cd5845edc28d401fa1969dd23448e4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14055/tests/oracle.patch @@ -0,0 +1,43 @@ +diff --git a/plugins/emacs/emacsclient.sh b/plugins/emacs/emacsclient.sh +index 172c0ae9..208eec71 100755 +--- a/plugins/emacs/emacsclient.sh ++++ b/plugins/emacs/emacsclient.sh +@@ -1,14 +1,33 @@ + #!/bin/sh + + emacsfun() { +- local cmd frames ++ local cmd frames arg tty + + # Build the Emacs Lisp command to check for suitable frames + # See https://www.gnu.org/software/emacs/manual/html_node/elisp/Frames.html#index-framep +- case "$*" in +- *-t*|*--tty*|*-nw*) cmd="(memq 't (mapcar 'framep (frame-list)))" ;; # if != nil, there are tty frames +- *) cmd="(delete 't (mapcar 'framep (frame-list)))" ;; # if != nil, there are graphical terminals (x, w32, ns) +- esac ++ for arg in "$@"; do ++ case "$arg" in ++ -t|--tty|-nw) tty=1; break ;; ++ esac ++ done ++ ++ if [ -n "$tty" ]; then ++ cmd="(memq 't (mapcar 'framep (frame-list)))" # if != nil, there are tty frames ++ else ++ cmd="(delete 't (mapcar 'framep (frame-list)))" # if != nil, there are graphical terminals (x, w32, ns) ++ fi ++ ++ # A tty frame needs the client to stay attached, so drop the --no-wait the ++ # `emacs` alias adds. Otherwise emacsclient returns at once and nothing opens. ++ if [ -n "$tty" ]; then ++ for arg do ++ shift ++ case "$arg" in ++ --no-wait) continue ;; ++ esac ++ set -- "$@" "$arg" ++ done ++ fi + + # Check if there are suitable frames + frames="$(emacsclient -a '' -n -e "$cmd" 2>/dev/null |sed 's/.*\x07//g' )" diff --git a/tasks/ohmyzsh__ohmyzsh-14055/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14055/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..3007348b30edf787046a068dae4d49d323c3585a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14055/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 87d4d40418438037e6e7576946cffa755d9b7fdf > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14055/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14055/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14055/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14057/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14057/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8136b488da7013cdfa8c70a811943de063f2f9ec --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14057/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8a5b3930889ea9b99450e600b5b5e00d0170cc09 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8a5b3930889ea9b99450e600b5b5e00d0170cc09 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8a5b3930889ea9b99450e600b5b5e00d0170cc09 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14057/instruction.md b/tasks/ohmyzsh__ohmyzsh-14057/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6d01d34639cd00573407505d14056cbe0b917d35 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14057/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** chore(gradle): update to version e7c881db + +## Description + +## Description + +Update for **gradle plugin**: update to version . +Check out the [list of changes](https://github.com/gradle/gradle-completion/compare/gradle:63578c9...gradle:e7c881d). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8a5b3930889e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14057/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14057/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..785363425513a8c80fe5a4e60fb25628a5e61c7b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14057/solution/patch.diff @@ -0,0 +1,85 @@ +diff --git a/.github/dependencies.yml b/.github/dependencies.yml +index 96d9991a..9ada5734 100644 +--- a/.github/dependencies.yml ++++ b/.github/dependencies.yml +@@ -12,7 +12,7 @@ dependencies: + plugins/gradle: + repo: gradle/gradle-completion + branch: master +- version: 63578c9bc56134b80766e88957ba0239e6be2343 ++ version: e7c881dbef7462bc35ad05328397e1582fe25cb8 + precopy: | + set -e + find . ! -name _gradle ! -name LICENSE -delete +diff --git a/plugins/gradle/_gradle b/plugins/gradle/_gradle +index aa7c8dec..05025ad9 100644 +--- a/plugins/gradle/_gradle ++++ b/plugins/gradle/_gradle +@@ -284,6 +284,9 @@ __gradle_subcommand() { + '-Dorg.gradle.debug.suspend=[]' \ + '-Dorg.gradle.debug=[]:org.gradle.debug:(true false)' \ + '-Dorg.gradle.dependency.verification=[Configures the dependency verification mode. Supported values are 'strict', 'lenient', or 'off'.]:org.gradle.dependency.verification:(strict lenient off)' \ ++ '-Dorg.gradle.isolated-projects.dangerously-ignore-problems=[]' \ ++ '-Dorg.gradle.isolated-projects.diagnostics=[]' \ ++ '-Dorg.gradle.isolated-projects=[Enables Isolated Projects. Projects are configured in parallel. Implies `--configuration-cache`.]' \ + '-Dorg.gradle.java.home=[]:org.gradle.java.home:_directories' \ + '-Dorg.gradle.java.installations.auto-detect=[]' \ + '-Dorg.gradle.java.installations.auto-download=[]' \ +@@ -299,8 +302,6 @@ __gradle_subcommand() { + '-Dorg.gradle.problems.report=[Enables the HTML problems report.]' \ + '-Dorg.gradle.projectcachedir=[Specifies the project-specific cache directory. Default is .gradle in the root project directory.]:org.gradle.projectcachedir:_directories' \ + '-Dorg.gradle.tooling.parallel=[]' \ +- '-Dorg.gradle.unsafe.isolated-projects.diagnostics=[]' \ +- '-Dorg.gradle.unsafe.isolated-projects=[]' \ + '-Dorg.gradle.vfs.verbose=[]' \ + '-Dorg.gradle.vfs.watch=[Enables file system watching. Reuses file system data for subsequent builds.]:org.gradle.vfs.watch:(true false)' \ + '-Dorg.gradle.warning.mode=[Specifies which mode of warnings to generate. Supported values are 'all', 'fail', 'summary' (default), or 'none'.]' \ +@@ -328,12 +329,14 @@ __gradle_subcommand() { + \*'--include-build[Includes the specified build in the composite.]:include build:_directories' \ + (--quiet,-q,--warn,-w,--debug,-d){-i,--info}'[Sets the log level to info.]' \ + \*{-I,--init-script}'[Specifies an initialization script.]:init script:_files -g \*.gradle(|.kts)' \ ++ (--no-isolated-projects)'--isolated-projects[Enables Isolated Projects. Projects are configured in parallel. Implies `--configuration-cache`. (incubating)]' \ + '--max-workers[Configures the maximum number of concurrent workers Gradle is allowed to use.]' \ + (--build-cache)'--no-build-cache[Disables the Gradle build cache.]' \ + (--configuration-cache)'--no-configuration-cache[Disables the configuration cache.]' \ + (--configure-on-demand)'--no-configure-on-demand[Disables the use of configuration on demand. (incubating)]' \ + (--continue)'--no-continue[Stops task execution after a task failure.]' \ + (--daemon)'--no-daemon[Runs the build without the Gradle daemon. Useful occasionally if you have configured Gradle to always run with the daemon by default.]' \ ++ (--isolated-projects)'--no-isolated-projects[Disables Isolated Projects. (incubating)]' \ + (--parallel)'--no-parallel[Disables parallel project execution.]' \ + (--problems-report)'--no-problems-report[Disables the HTML problems report. (incubating)]' \ + {-a,--no-rebuild}'[Disables rebuilding of project dependencies.]' \ +@@ -421,6 +424,9 @@ _gradle() { + '-Dorg.gradle.debug.suspend=[]:->argument-expected' \ + '-Dorg.gradle.debug=[]:org.gradle.debug:(true false):->argument-expected' \ + '-Dorg.gradle.dependency.verification=[Configures the dependency verification mode. Supported values are 'strict', 'lenient', or 'off'.]:org.gradle.dependency.verification:(strict lenient off):->argument-expected' \ ++ '-Dorg.gradle.isolated-projects.dangerously-ignore-problems=[]:->argument-expected' \ ++ '-Dorg.gradle.isolated-projects.diagnostics=[]:->argument-expected' \ ++ '-Dorg.gradle.isolated-projects=[Enables Isolated Projects. Projects are configured in parallel. Implies `--configuration-cache`.]:->argument-expected' \ + '-Dorg.gradle.java.home=[]:org.gradle.java.home:_directories:->argument-expected' \ + '-Dorg.gradle.java.installations.auto-detect=[]:->argument-expected' \ + '-Dorg.gradle.java.installations.auto-download=[]:->argument-expected' \ +@@ -436,8 +442,6 @@ _gradle() { + '-Dorg.gradle.problems.report=[Enables the HTML problems report.]:->argument-expected' \ + '-Dorg.gradle.projectcachedir=[Specifies the project-specific cache directory. Default is .gradle in the root project directory.]:org.gradle.projectcachedir:_directories:->argument-expected' \ + '-Dorg.gradle.tooling.parallel=[]:->argument-expected' \ +- '-Dorg.gradle.unsafe.isolated-projects.diagnostics=[]:->argument-expected' \ +- '-Dorg.gradle.unsafe.isolated-projects=[]:->argument-expected' \ + '-Dorg.gradle.vfs.verbose=[]:->argument-expected' \ + '-Dorg.gradle.vfs.watch=[Enables file system watching. Reuses file system data for subsequent builds.]:org.gradle.vfs.watch:(true false):->argument-expected' \ + '-Dorg.gradle.warning.mode=[Specifies which mode of warnings to generate. Supported values are 'all', 'fail', 'summary' (default), or 'none'.]:->argument-expected' \ +@@ -466,12 +470,14 @@ _gradle() { + \*'--include-build[Includes the specified build in the composite.]:include build:_directories:->argument-expected' \ + (--quiet,-q,--warn,-w,--debug,-d){-i,--info}'[Sets the log level to info.]' \ + \*{-I,--init-script}'[Specifies an initialization script.]:init script:_files -g \*.gradle(|.kts):->argument-expected' \ ++ (--no-isolated-projects)'--isolated-projects[Enables Isolated Projects. Projects are configured in parallel. Implies `--configuration-cache`. (incubating)]' \ + '--max-workers[Configures the maximum number of concurrent workers Gradle is allowed to use.]:->argument-expected' \ + (--build-cache)'--no-build-cache[Disables the Gradle build cache.]' \ + (--configuration-cache)'--no-configuration-cache[Disables the configuration cache.]' \ + (--configure-on-demand)'--no-configure-on-demand[Disables the use of configuration on demand. (incubating)]' \ + (--continue)'--no-continue[Stops task execution after a task failure.]' \ + (--daemon)'--no-daemon[Runs the build without the Gradle daemon. Useful occasionally if you have configured Gradle to always run with the daemon by default.]' \ ++ (--isolated-projects)'--no-isolated-projects[Disables Isolated Projects. (incubating)]' \ + (--parallel)'--no-parallel[Disables parallel project execution.]' \ + (--problems-report)'--no-problems-report[Disables the HTML problems report. (incubating)]' \ + {-a,--no-rebuild}'[Disables rebuilding of project dependencies.]' \ diff --git a/tasks/ohmyzsh__ohmyzsh-14057/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14057/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14057/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14057/task.toml b/tasks/ohmyzsh__ohmyzsh-14057/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5a69649c9955f4aeaaae13f2dcdd5e56c6f63efe --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14057/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14057" +description = "chore(gradle): update to version e7c881db" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "8a5b3930889ea9b99450e600b5b5e00d0170cc09" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14057" +source_access = "auto" +built_at = "2026-11-16T16:09:56.988674+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:bb130aff08bf37cd7adb36a23254ce6fef87da2e383049288f09c61e3b63b280" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-07T08:19:34Z" +diff_format = "unified" +context_files = [ + ".github/dependencies.yml", + "plugins/gradle/_gradle", +] +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.979074+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c1b1cde3df3a573fd996177d848820f67d4994ea740b284cdfd2070efa132d41" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14057/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14057/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14057/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14057/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14057/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6d01d34639cd00573407505d14056cbe0b917d35 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14057/tests/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** chore(gradle): update to version e7c881db + +## Description + +## Description + +Update for **gradle plugin**: update to version . +Check out the [list of changes](https://github.com/gradle/gradle-completion/compare/gradle:63578c9...gradle:e7c881d). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8a5b3930889e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14057/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14057/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..785363425513a8c80fe5a4e60fb25628a5e61c7b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14057/tests/oracle.patch @@ -0,0 +1,85 @@ +diff --git a/.github/dependencies.yml b/.github/dependencies.yml +index 96d9991a..9ada5734 100644 +--- a/.github/dependencies.yml ++++ b/.github/dependencies.yml +@@ -12,7 +12,7 @@ dependencies: + plugins/gradle: + repo: gradle/gradle-completion + branch: master +- version: 63578c9bc56134b80766e88957ba0239e6be2343 ++ version: e7c881dbef7462bc35ad05328397e1582fe25cb8 + precopy: | + set -e + find . ! -name _gradle ! -name LICENSE -delete +diff --git a/plugins/gradle/_gradle b/plugins/gradle/_gradle +index aa7c8dec..05025ad9 100644 +--- a/plugins/gradle/_gradle ++++ b/plugins/gradle/_gradle +@@ -284,6 +284,9 @@ __gradle_subcommand() { + '-Dorg.gradle.debug.suspend=[]' \ + '-Dorg.gradle.debug=[]:org.gradle.debug:(true false)' \ + '-Dorg.gradle.dependency.verification=[Configures the dependency verification mode. Supported values are 'strict', 'lenient', or 'off'.]:org.gradle.dependency.verification:(strict lenient off)' \ ++ '-Dorg.gradle.isolated-projects.dangerously-ignore-problems=[]' \ ++ '-Dorg.gradle.isolated-projects.diagnostics=[]' \ ++ '-Dorg.gradle.isolated-projects=[Enables Isolated Projects. Projects are configured in parallel. Implies `--configuration-cache`.]' \ + '-Dorg.gradle.java.home=[]:org.gradle.java.home:_directories' \ + '-Dorg.gradle.java.installations.auto-detect=[]' \ + '-Dorg.gradle.java.installations.auto-download=[]' \ +@@ -299,8 +302,6 @@ __gradle_subcommand() { + '-Dorg.gradle.problems.report=[Enables the HTML problems report.]' \ + '-Dorg.gradle.projectcachedir=[Specifies the project-specific cache directory. Default is .gradle in the root project directory.]:org.gradle.projectcachedir:_directories' \ + '-Dorg.gradle.tooling.parallel=[]' \ +- '-Dorg.gradle.unsafe.isolated-projects.diagnostics=[]' \ +- '-Dorg.gradle.unsafe.isolated-projects=[]' \ + '-Dorg.gradle.vfs.verbose=[]' \ + '-Dorg.gradle.vfs.watch=[Enables file system watching. Reuses file system data for subsequent builds.]:org.gradle.vfs.watch:(true false)' \ + '-Dorg.gradle.warning.mode=[Specifies which mode of warnings to generate. Supported values are 'all', 'fail', 'summary' (default), or 'none'.]' \ +@@ -328,12 +329,14 @@ __gradle_subcommand() { + \*'--include-build[Includes the specified build in the composite.]:include build:_directories' \ + (--quiet,-q,--warn,-w,--debug,-d){-i,--info}'[Sets the log level to info.]' \ + \*{-I,--init-script}'[Specifies an initialization script.]:init script:_files -g \*.gradle(|.kts)' \ ++ (--no-isolated-projects)'--isolated-projects[Enables Isolated Projects. Projects are configured in parallel. Implies `--configuration-cache`. (incubating)]' \ + '--max-workers[Configures the maximum number of concurrent workers Gradle is allowed to use.]' \ + (--build-cache)'--no-build-cache[Disables the Gradle build cache.]' \ + (--configuration-cache)'--no-configuration-cache[Disables the configuration cache.]' \ + (--configure-on-demand)'--no-configure-on-demand[Disables the use of configuration on demand. (incubating)]' \ + (--continue)'--no-continue[Stops task execution after a task failure.]' \ + (--daemon)'--no-daemon[Runs the build without the Gradle daemon. Useful occasionally if you have configured Gradle to always run with the daemon by default.]' \ ++ (--isolated-projects)'--no-isolated-projects[Disables Isolated Projects. (incubating)]' \ + (--parallel)'--no-parallel[Disables parallel project execution.]' \ + (--problems-report)'--no-problems-report[Disables the HTML problems report. (incubating)]' \ + {-a,--no-rebuild}'[Disables rebuilding of project dependencies.]' \ +@@ -421,6 +424,9 @@ _gradle() { + '-Dorg.gradle.debug.suspend=[]:->argument-expected' \ + '-Dorg.gradle.debug=[]:org.gradle.debug:(true false):->argument-expected' \ + '-Dorg.gradle.dependency.verification=[Configures the dependency verification mode. Supported values are 'strict', 'lenient', or 'off'.]:org.gradle.dependency.verification:(strict lenient off):->argument-expected' \ ++ '-Dorg.gradle.isolated-projects.dangerously-ignore-problems=[]:->argument-expected' \ ++ '-Dorg.gradle.isolated-projects.diagnostics=[]:->argument-expected' \ ++ '-Dorg.gradle.isolated-projects=[Enables Isolated Projects. Projects are configured in parallel. Implies `--configuration-cache`.]:->argument-expected' \ + '-Dorg.gradle.java.home=[]:org.gradle.java.home:_directories:->argument-expected' \ + '-Dorg.gradle.java.installations.auto-detect=[]:->argument-expected' \ + '-Dorg.gradle.java.installations.auto-download=[]:->argument-expected' \ +@@ -436,8 +442,6 @@ _gradle() { + '-Dorg.gradle.problems.report=[Enables the HTML problems report.]:->argument-expected' \ + '-Dorg.gradle.projectcachedir=[Specifies the project-specific cache directory. Default is .gradle in the root project directory.]:org.gradle.projectcachedir:_directories:->argument-expected' \ + '-Dorg.gradle.tooling.parallel=[]:->argument-expected' \ +- '-Dorg.gradle.unsafe.isolated-projects.diagnostics=[]:->argument-expected' \ +- '-Dorg.gradle.unsafe.isolated-projects=[]:->argument-expected' \ + '-Dorg.gradle.vfs.verbose=[]:->argument-expected' \ + '-Dorg.gradle.vfs.watch=[Enables file system watching. Reuses file system data for subsequent builds.]:org.gradle.vfs.watch:(true false):->argument-expected' \ + '-Dorg.gradle.warning.mode=[Specifies which mode of warnings to generate. Supported values are 'all', 'fail', 'summary' (default), or 'none'.]:->argument-expected' \ +@@ -466,12 +470,14 @@ _gradle() { + \*'--include-build[Includes the specified build in the composite.]:include build:_directories:->argument-expected' \ + (--quiet,-q,--warn,-w,--debug,-d){-i,--info}'[Sets the log level to info.]' \ + \*{-I,--init-script}'[Specifies an initialization script.]:init script:_files -g \*.gradle(|.kts):->argument-expected' \ ++ (--no-isolated-projects)'--isolated-projects[Enables Isolated Projects. Projects are configured in parallel. Implies `--configuration-cache`. (incubating)]' \ + '--max-workers[Configures the maximum number of concurrent workers Gradle is allowed to use.]:->argument-expected' \ + (--build-cache)'--no-build-cache[Disables the Gradle build cache.]' \ + (--configuration-cache)'--no-configuration-cache[Disables the configuration cache.]' \ + (--configure-on-demand)'--no-configure-on-demand[Disables the use of configuration on demand. (incubating)]' \ + (--continue)'--no-continue[Stops task execution after a task failure.]' \ + (--daemon)'--no-daemon[Runs the build without the Gradle daemon. Useful occasionally if you have configured Gradle to always run with the daemon by default.]' \ ++ (--isolated-projects)'--no-isolated-projects[Disables Isolated Projects. (incubating)]' \ + (--parallel)'--no-parallel[Disables parallel project execution.]' \ + (--problems-report)'--no-problems-report[Disables the HTML problems report. (incubating)]' \ + {-a,--no-rebuild}'[Disables rebuilding of project dependencies.]' \ diff --git a/tasks/ohmyzsh__ohmyzsh-14057/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14057/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6bebdc3228f841e68d999e3e1542c97607d2d0cb --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14057/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 8a5b3930889ea9b99450e600b5b5e00d0170cc09 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14057/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14057/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14057/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14058/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14058/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8136b488da7013cdfa8c70a811943de063f2f9ec --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14058/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8a5b3930889ea9b99450e600b5b5e00d0170cc09 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8a5b3930889ea9b99450e600b5b5e00d0170cc09 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8a5b3930889ea9b99450e600b5b5e00d0170cc09 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14058/instruction.md b/tasks/ohmyzsh__ohmyzsh-14058/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4c0f3d951ff12e979807f9508f3018c6cfa1a444 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14058/instruction.md @@ -0,0 +1,58 @@ +# Issue + +**Title:** fix(symfony6): do not evaluate the typed command line + +## Description + +The `symfony6` plugin is a copy of the completion script shipped by `symfony/console`, and it has not been updated since it was added in June 2024. Two fixes made upstream since then are missing, one of them with a security impact. + +### The completion runs what you type + +The completion request is assembled as a string from the raw words of the command line, then passed to `eval`. Any command substitution present in a word is therefore executed by the completion, before the user validates the line. + +Reproducer, with the plugin loaded and a `bin/console` in the current directory: + +``` +$ bin/console $(id>/tmp/pwned) ca +$ cat /tmp/pwned +uid=501(jerome) gid=20(staff) ... +``` + +The file is created without the line ever being run. Pressing Tab is enough. + +The request is now run as an array of arguments, without being read again by the shell, and `_describe` is called directly instead of through `eval`. The alias of the command is resolved explicitly with `${aliases[$sf_cmd]}`, since that was the only useful effect of the `eval`. + +### Completion broken when SHELL_VERBOSITY=-1 + +The request now runs with `SHELL_VERBOSITY=0`, so completion keeps working for users who exported `SHELL_VERBOSITY=-1`. + +### About this change + +Both fixes are ported verbatim from Symfony, they are not written for this plugin: + +- symfony/symfony#65818, do not evaluate the command line in the zsh completion +- symfony/symfony#63859, fix shell completion when `SHELL_VERBOSITY=-1` + +The resulting file is byte for byte the current `src/Symfony/Component/Console/Resources/completion.zsh` of the Symfony 6.4 branch, with the two template placeholders substituted as the plugin already does: + +``` +git show 6.4:src/Symfony/Component/Console/Resources/completion.zsh \ + | sed 's/{{ COMMAND_NAME }}/console/g; s/{{ VERSION }}/1/' \ + | diff - plugins/symfony6/symfony6.plugin.zsh +``` + +The plugin already carries symfony/symfony#47464 and symfony/symfony#50110, so those needed no porting. + +### How it was tested + +`zsh -n` on the file, then in a real shell driven through `zpty`, against symfony-demo running `symfony/console` 8.1: `bin/console cache:cl` completes, `bin/console cache:clear --env=` still gets the `-P` flag prefix, and the same runs fine with `SHELL_VERBOSITY=-1` exported. The reproducer above creates the file before the change and no longer creates it after. + +### Note on #13177 + +#13177 proposes to merge the three symfony plugins into one. It is untouched since June 2025 and it rewrites the same file, so it would need to carry these fixes over. This PR is independent of it and does not depend on its outcome. + +AI-assisted: Claude Code helped port the upstream diff and build the `zpty` test harness. I reviewed and ran everything myself. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8a5b3930889e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14058/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14058/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9ac6378d9b495f911e2d7cbb5b3ccad1bdc6a2d0 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14058/solution/patch.diff @@ -0,0 +1,74 @@ +diff --git a/plugins/symfony6/symfony6.plugin.zsh b/plugins/symfony6/symfony6.plugin.zsh +index ed7dbe60..e2424376 100644 +--- a/plugins/symfony6/symfony6.plugin.zsh ++++ b/plugins/symfony6/symfony6.plugin.zsh +@@ -15,8 +15,8 @@ + # - https://github.com/symfony/symfony/blob/5.4/src/Symfony/Component/Console/Resources/completion.bash + # + _sf_console() { +- local lastParam flagPrefix requestComp out comp +- local -a completions ++ local lastParam out comp sf_cmd ++ local -a completions flagPrefix requestComp inputs + + # The user could have moved the cursor backwards on the command-line. + # We need to trigger completion from the $CURRENT location, so we need +@@ -29,11 +29,20 @@ _sf_console() { + setopt local_options BASH_REMATCH + if [[ "${lastParam}" =~ '-.*=' ]]; then + # We are dealing with a flag with an = +- flagPrefix="-P ${BASH_REMATCH}" ++ flagPrefix=(-P "${BASH_REMATCH}") + fi + +- # Prepare the command to obtain completions +- requestComp="${words[0]} ${words[1]} _complete --no-interaction -szsh -a1 -c$((CURRENT-1))" i="" ++ # Prepare the command to obtain completions. An alias is resolved here, ++ # because the request is no longer read again by the shell. ++ sf_cmd="${words[1]}" ++ if [[ -n "${aliases[$sf_cmd]}" ]]; then ++ requestComp=(${(z)aliases[$sf_cmd]}) ++ else ++ requestComp=(${~sf_cmd}) ++ fi ++ ++ requestComp+=(_complete --no-interaction -szsh -a1 "-c$((CURRENT-1))") ++ + for w in ${words[@]}; do + w=$(printf -- '%b' "$w") + # remove quotes from typed values +@@ -47,19 +56,18 @@ _sf_console() { + fi + # empty values are ignored + if [ ! -z "$w" ]; then +- i="${i}-i${w} " ++ inputs+=("-i$w") + fi + done + + # Ensure at least 1 input +- if [ "${i}" = "" ]; then +- requestComp="${requestComp} -i\" \"" +- else +- requestComp="${requestComp} ${i}" ++ if (( ! $#inputs )); then ++ inputs=(-i' ') + fi + +- # Use eval to handle any environment variables and such +- out=$(eval ${requestComp} 2>/dev/null) ++ # The request is run without being read again by the shell, so that a ++ # "$(...)" or a backtick typed on the command line is not executed ++ out=$(SHELL_VERBOSITY=0 "${requestComp[@]}" "${inputs[@]}" 2>/dev/null) + + while IFS='\n' read -r comp; do + if [ -n "$comp" ]; then +@@ -75,7 +83,7 @@ _sf_console() { + done < <(printf "%s\n" "${out[@]}") + + # Let inbuilt _describe handle completions +- eval _describe "completions" completions $flagPrefix ++ _describe "completions" completions "${flagPrefix[@]}" + return $? + } + diff --git a/tasks/ohmyzsh__ohmyzsh-14058/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14058/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14058/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14058/task.toml b/tasks/ohmyzsh__ohmyzsh-14058/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..18c5ed8da84ee1defdb16a0638f3cad0199ecf2e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14058/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14058" +description = "fix(symfony6): do not evaluate the typed command line" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "8a5b3930889ea9b99450e600b5b5e00d0170cc09" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14058" +source_access = "auto" +built_at = "2026-11-16T16:09:56.985092+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2e1007a7132f3f86407b81e24b0155174a0b3bec8191fdf25db8ca2672d7e275" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-06T14:02:48Z" +diff_format = "unified" +context_files = [ + "plugins/symfony6/symfony6.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 34 +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.979604+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c1b1cde3df3a573fd996177d848820f67d4994ea740b284cdfd2070efa132d41" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14058/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14058/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14058/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14058/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14058/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4c0f3d951ff12e979807f9508f3018c6cfa1a444 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14058/tests/instruction.md @@ -0,0 +1,58 @@ +# Issue + +**Title:** fix(symfony6): do not evaluate the typed command line + +## Description + +The `symfony6` plugin is a copy of the completion script shipped by `symfony/console`, and it has not been updated since it was added in June 2024. Two fixes made upstream since then are missing, one of them with a security impact. + +### The completion runs what you type + +The completion request is assembled as a string from the raw words of the command line, then passed to `eval`. Any command substitution present in a word is therefore executed by the completion, before the user validates the line. + +Reproducer, with the plugin loaded and a `bin/console` in the current directory: + +``` +$ bin/console $(id>/tmp/pwned) ca +$ cat /tmp/pwned +uid=501(jerome) gid=20(staff) ... +``` + +The file is created without the line ever being run. Pressing Tab is enough. + +The request is now run as an array of arguments, without being read again by the shell, and `_describe` is called directly instead of through `eval`. The alias of the command is resolved explicitly with `${aliases[$sf_cmd]}`, since that was the only useful effect of the `eval`. + +### Completion broken when SHELL_VERBOSITY=-1 + +The request now runs with `SHELL_VERBOSITY=0`, so completion keeps working for users who exported `SHELL_VERBOSITY=-1`. + +### About this change + +Both fixes are ported verbatim from Symfony, they are not written for this plugin: + +- symfony/symfony#65818, do not evaluate the command line in the zsh completion +- symfony/symfony#63859, fix shell completion when `SHELL_VERBOSITY=-1` + +The resulting file is byte for byte the current `src/Symfony/Component/Console/Resources/completion.zsh` of the Symfony 6.4 branch, with the two template placeholders substituted as the plugin already does: + +``` +git show 6.4:src/Symfony/Component/Console/Resources/completion.zsh \ + | sed 's/{{ COMMAND_NAME }}/console/g; s/{{ VERSION }}/1/' \ + | diff - plugins/symfony6/symfony6.plugin.zsh +``` + +The plugin already carries symfony/symfony#47464 and symfony/symfony#50110, so those needed no porting. + +### How it was tested + +`zsh -n` on the file, then in a real shell driven through `zpty`, against symfony-demo running `symfony/console` 8.1: `bin/console cache:cl` completes, `bin/console cache:clear --env=` still gets the `-P` flag prefix, and the same runs fine with `SHELL_VERBOSITY=-1` exported. The reproducer above creates the file before the change and no longer creates it after. + +### Note on #13177 + +#13177 proposes to merge the three symfony plugins into one. It is untouched since June 2025 and it rewrites the same file, so it would need to carry these fixes over. This PR is independent of it and does not depend on its outcome. + +AI-assisted: Claude Code helped port the upstream diff and build the `zpty` test harness. I reviewed and ran everything myself. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8a5b3930889e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14058/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14058/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9ac6378d9b495f911e2d7cbb5b3ccad1bdc6a2d0 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14058/tests/oracle.patch @@ -0,0 +1,74 @@ +diff --git a/plugins/symfony6/symfony6.plugin.zsh b/plugins/symfony6/symfony6.plugin.zsh +index ed7dbe60..e2424376 100644 +--- a/plugins/symfony6/symfony6.plugin.zsh ++++ b/plugins/symfony6/symfony6.plugin.zsh +@@ -15,8 +15,8 @@ + # - https://github.com/symfony/symfony/blob/5.4/src/Symfony/Component/Console/Resources/completion.bash + # + _sf_console() { +- local lastParam flagPrefix requestComp out comp +- local -a completions ++ local lastParam out comp sf_cmd ++ local -a completions flagPrefix requestComp inputs + + # The user could have moved the cursor backwards on the command-line. + # We need to trigger completion from the $CURRENT location, so we need +@@ -29,11 +29,20 @@ _sf_console() { + setopt local_options BASH_REMATCH + if [[ "${lastParam}" =~ '-.*=' ]]; then + # We are dealing with a flag with an = +- flagPrefix="-P ${BASH_REMATCH}" ++ flagPrefix=(-P "${BASH_REMATCH}") + fi + +- # Prepare the command to obtain completions +- requestComp="${words[0]} ${words[1]} _complete --no-interaction -szsh -a1 -c$((CURRENT-1))" i="" ++ # Prepare the command to obtain completions. An alias is resolved here, ++ # because the request is no longer read again by the shell. ++ sf_cmd="${words[1]}" ++ if [[ -n "${aliases[$sf_cmd]}" ]]; then ++ requestComp=(${(z)aliases[$sf_cmd]}) ++ else ++ requestComp=(${~sf_cmd}) ++ fi ++ ++ requestComp+=(_complete --no-interaction -szsh -a1 "-c$((CURRENT-1))") ++ + for w in ${words[@]}; do + w=$(printf -- '%b' "$w") + # remove quotes from typed values +@@ -47,19 +56,18 @@ _sf_console() { + fi + # empty values are ignored + if [ ! -z "$w" ]; then +- i="${i}-i${w} " ++ inputs+=("-i$w") + fi + done + + # Ensure at least 1 input +- if [ "${i}" = "" ]; then +- requestComp="${requestComp} -i\" \"" +- else +- requestComp="${requestComp} ${i}" ++ if (( ! $#inputs )); then ++ inputs=(-i' ') + fi + +- # Use eval to handle any environment variables and such +- out=$(eval ${requestComp} 2>/dev/null) ++ # The request is run without being read again by the shell, so that a ++ # "$(...)" or a backtick typed on the command line is not executed ++ out=$(SHELL_VERBOSITY=0 "${requestComp[@]}" "${inputs[@]}" 2>/dev/null) + + while IFS='\n' read -r comp; do + if [ -n "$comp" ]; then +@@ -75,7 +83,7 @@ _sf_console() { + done < <(printf "%s\n" "${out[@]}") + + # Let inbuilt _describe handle completions +- eval _describe "completions" completions $flagPrefix ++ _describe "completions" completions "${flagPrefix[@]}" + return $? + } + diff --git a/tasks/ohmyzsh__ohmyzsh-14058/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14058/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6bebdc3228f841e68d999e3e1542c97607d2d0cb --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14058/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 8a5b3930889ea9b99450e600b5b5e00d0170cc09 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14058/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14058/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14058/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14060/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14060/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8136b488da7013cdfa8c70a811943de063f2f9ec --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14060/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8a5b3930889ea9b99450e600b5b5e00d0170cc09 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8a5b3930889ea9b99450e600b5b5e00d0170cc09 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8a5b3930889ea9b99450e600b5b5e00d0170cc09 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14060/instruction.md b/tasks/ohmyzsh__ohmyzsh-14060/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..62f4b10e4760a3d0b8dfc4f390cb95615f6e1ea9 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14060/instruction.md @@ -0,0 +1,67 @@ +# Issue + +**Title:** chore(deps): bump step-security/harden-runner from 2.21.0 to 2.21.1 in the gha-minor group + +## Description + +Bumps the gha-minor group with 1 update: [step-security/harden-runner](https://github.com/step-security/harden-runner). + +Updates `step-security/harden-runner` from 2.21.0 to 2.21.1 +
      +Release notes +

      Sourced from step-security/harden-runner's releases.

      +
      +

      v2.21.1

      +

      What's Changed

      +
        +
      • Improved performance of the disable-sudo feature.
      • +
      • Fixed an issue in the Community tier where new endpoints required by the GitHub Actions runner were not being implicitly allowed in block mode.
      • +
      • Fixed the Harden-Runner post step failing on Linux distributions that do not have a merged /usr filesystem layout (for example Debian 11), where /usr/bin/echo does not exist. This mainly affected self-hosted runners.
      • +
      • Documentation updates: clarified which features are in the Community (free) vs Enterprise tier.
      • +
      +

      Full Changelog: https://github.com/step-security/harden-runner/compare/v2.21.0...v2.21.1

      +
      +
      +
      +Commits +
        +
      • e14015d Merge pull request #690 from step-security/rc-43
      • +
      • 9001249 docs: update harden-runner version pin to v2.21.0 in getting started example
      • +
      • a447fba docs: expand enterprise feature list and document custom VM and ubuntu-slim l...
      • +
      • b0eaf8d docs: clarify community vs enterprise tiers and add maintained actions section
      • +
      • 063e8e3 Merge pull request #687 from rohan-stepsecurity/rp/fix/bin-echo-fallback
      • +
      • f46bdc1 chore: bump agent-ebpf to v1.9.1 and agent to v0.16.3
      • +
      • 42e6daa fix: fall back to /bin/echo for non-usr-merged distros
      • +
      • See full diff in compare view
      • +
      +
      +
      + +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=step-security/harden-runner&package-manager=github_actions&previous-version=2.21.0&new-version=2.21.1)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) + +Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. + +[//]: # (dependabot-automerge-start) +[//]: # (dependabot-automerge-end) + +--- + +
      +Dependabot commands and options +
      + +You can trigger Dependabot actions by commenting on this PR: +- `@dependabot rebase` will rebase this PR +- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it +- `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency +- `@dependabot ignore major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) +- `@dependabot ignore minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) +- `@dependabot ignore ` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) +- `@dependabot unignore ` will remove all of the ignore conditions of the specified dependency +- `@dependabot unignore ` will remove the ignore condition of the specified dependency and ignore conditions + +
      + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8a5b3930889e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14060/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14060/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..08268fbc5c8b39ff2c6c9a17194911d19d95f5d5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14060/solution/patch.diff @@ -0,0 +1,74 @@ +diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml +index 2389544f..d4351ed5 100644 +--- a/.github/workflows/dependencies.yml ++++ b/.github/workflows/dependencies.yml +@@ -16,7 +16,7 @@ jobs: + contents: write # this is needed to push commits and branches + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 ++ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + +diff --git a/.github/workflows/installer.yml b/.github/workflows/installer.yml +index cb5acc54..1b26b2c9 100644 +--- a/.github/workflows/installer.yml ++++ b/.github/workflows/installer.yml +@@ -26,7 +26,7 @@ jobs: + - macos-latest + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 ++ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + +@@ -47,7 +47,7 @@ jobs: + - test + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 ++ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + +diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml +index 6354caae..f16a9efc 100644 +--- a/.github/workflows/main.yml ++++ b/.github/workflows/main.yml +@@ -24,7 +24,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 ++ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + +diff --git a/.github/workflows/project.yml b/.github/workflows/project.yml +index d3a2cd8f..4be8e04d 100644 +--- a/.github/workflows/project.yml ++++ b/.github/workflows/project.yml +@@ -17,7 +17,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 ++ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + - name: Authenticate as @ohmyzsh +diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml +index 9f35b4f5..06aa8b98 100644 +--- a/.github/workflows/scorecard.yml ++++ b/.github/workflows/scorecard.yml +@@ -36,7 +36,7 @@ jobs: + + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 ++ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + diff --git a/tasks/ohmyzsh__ohmyzsh-14060/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14060/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14060/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14060/task.toml b/tasks/ohmyzsh__ohmyzsh-14060/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8f43614f3cc666ae4483c4222641e7bbfc4f72fc --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14060/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14060" +description = "chore(deps): bump step-security/harden-runner from 2.21.0 to 2.21.1 in the gha-minor group" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "8a5b3930889ea9b99450e600b5b5e00d0170cc09" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14060" +source_access = "auto" +built_at = "2026-11-16T16:09:56.986981+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:a43b117dc872e8e21bf17684f3b09bd2fccb144fd97c3e38c7881e14af583ef2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-07T08:19:48Z" +diff_format = "unified" +context_files = [ + ".github/workflows/dependencies.yml", + ".github/workflows/installer.yml", + ".github/workflows/main.yml", + ".github/workflows/project.yml", + ".github/workflows/scorecard.yml", +] +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.980205+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c1b1cde3df3a573fd996177d848820f67d4994ea740b284cdfd2070efa132d41" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14060/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14060/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14060/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14060/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14060/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..62f4b10e4760a3d0b8dfc4f390cb95615f6e1ea9 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14060/tests/instruction.md @@ -0,0 +1,67 @@ +# Issue + +**Title:** chore(deps): bump step-security/harden-runner from 2.21.0 to 2.21.1 in the gha-minor group + +## Description + +Bumps the gha-minor group with 1 update: [step-security/harden-runner](https://github.com/step-security/harden-runner). + +Updates `step-security/harden-runner` from 2.21.0 to 2.21.1 +
      +Release notes +

      Sourced from step-security/harden-runner's releases.

      +
      +

      v2.21.1

      +

      What's Changed

      +
        +
      • Improved performance of the disable-sudo feature.
      • +
      • Fixed an issue in the Community tier where new endpoints required by the GitHub Actions runner were not being implicitly allowed in block mode.
      • +
      • Fixed the Harden-Runner post step failing on Linux distributions that do not have a merged /usr filesystem layout (for example Debian 11), where /usr/bin/echo does not exist. This mainly affected self-hosted runners.
      • +
      • Documentation updates: clarified which features are in the Community (free) vs Enterprise tier.
      • +
      +

      Full Changelog: https://github.com/step-security/harden-runner/compare/v2.21.0...v2.21.1

      +
      +
      +
      +Commits +
        +
      • e14015d Merge pull request #690 from step-security/rc-43
      • +
      • 9001249 docs: update harden-runner version pin to v2.21.0 in getting started example
      • +
      • a447fba docs: expand enterprise feature list and document custom VM and ubuntu-slim l...
      • +
      • b0eaf8d docs: clarify community vs enterprise tiers and add maintained actions section
      • +
      • 063e8e3 Merge pull request #687 from rohan-stepsecurity/rp/fix/bin-echo-fallback
      • +
      • f46bdc1 chore: bump agent-ebpf to v1.9.1 and agent to v0.16.3
      • +
      • 42e6daa fix: fall back to /bin/echo for non-usr-merged distros
      • +
      • See full diff in compare view
      • +
      +
      +
      + +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=step-security/harden-runner&package-manager=github_actions&previous-version=2.21.0&new-version=2.21.1)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) + +Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. + +[//]: # (dependabot-automerge-start) +[//]: # (dependabot-automerge-end) + +--- + +
      +Dependabot commands and options +
      + +You can trigger Dependabot actions by commenting on this PR: +- `@dependabot rebase` will rebase this PR +- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it +- `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency +- `@dependabot ignore major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) +- `@dependabot ignore minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) +- `@dependabot ignore ` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) +- `@dependabot unignore ` will remove all of the ignore conditions of the specified dependency +- `@dependabot unignore ` will remove the ignore condition of the specified dependency and ignore conditions + +
      + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8a5b3930889e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14060/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14060/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..08268fbc5c8b39ff2c6c9a17194911d19d95f5d5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14060/tests/oracle.patch @@ -0,0 +1,74 @@ +diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml +index 2389544f..d4351ed5 100644 +--- a/.github/workflows/dependencies.yml ++++ b/.github/workflows/dependencies.yml +@@ -16,7 +16,7 @@ jobs: + contents: write # this is needed to push commits and branches + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 ++ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + +diff --git a/.github/workflows/installer.yml b/.github/workflows/installer.yml +index cb5acc54..1b26b2c9 100644 +--- a/.github/workflows/installer.yml ++++ b/.github/workflows/installer.yml +@@ -26,7 +26,7 @@ jobs: + - macos-latest + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 ++ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + +@@ -47,7 +47,7 @@ jobs: + - test + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 ++ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + +diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml +index 6354caae..f16a9efc 100644 +--- a/.github/workflows/main.yml ++++ b/.github/workflows/main.yml +@@ -24,7 +24,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 ++ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + +diff --git a/.github/workflows/project.yml b/.github/workflows/project.yml +index d3a2cd8f..4be8e04d 100644 +--- a/.github/workflows/project.yml ++++ b/.github/workflows/project.yml +@@ -17,7 +17,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 ++ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + - name: Authenticate as @ohmyzsh +diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml +index 9f35b4f5..06aa8b98 100644 +--- a/.github/workflows/scorecard.yml ++++ b/.github/workflows/scorecard.yml +@@ -36,7 +36,7 @@ jobs: + + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@05e31511f85b41b11d1cf0ef85d0992719546e2c # v2.21.0 ++ uses: step-security/harden-runner@e14015d583714f6e62063499dc959a02595150a1 # v2.21.1 + with: + egress-policy: audit + diff --git a/tasks/ohmyzsh__ohmyzsh-14060/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14060/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6bebdc3228f841e68d999e3e1542c97607d2d0cb --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14060/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 8a5b3930889ea9b99450e600b5b5e00d0170cc09 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14060/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14060/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14060/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14061/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14061/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7f85d14cf0ec2432431ce51881570fbac46b8bf6 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14061/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 426650fbe8943879af72703556ae5d1eb2eac734 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 426650fbe8943879af72703556ae5d1eb2eac734 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 426650fbe8943879af72703556ae5d1eb2eac734 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14061/instruction.md b/tasks/ohmyzsh__ohmyzsh-14061/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ba501360adb6f7ec9195cbab440190a5ecf202ff --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14061/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** perf(init): check zcompdump metadata without forking grep + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- The zcompdump metadata lines (`#omz revision:` and `#omz fpath:`) were checked with two `grep -Fx` runs over the whole dump on every startup, plus a third grep after `compinit`. +- Read the dump once in zsh and test membership with `(Ie)` instead. The check after `compinit` is kept, since `compinit` can regenerate the dump and drop the metadata. +- No behaviour change: the dump is still deleted when the revision or `$fpath` changes, and the metadata is still appended when missing. + +## Other comments: + +First of a series of small startup-time PRs. Profiled with an isolated `ZDOTDIR` on macOS arm64, zsh 5.9, default template, warm dump: this step takes the metadata check + append from 17.5 ms to 3.3 ms per interactive start. Roughly 80% of what Oh My Zsh itself adds to a warm startup is process forks plus `compaudit`, so each PR in the series removes one fork. + +Verified: cold start regenerates the dump with metadata, changing `plugins=()` regenerates it, a stale `#files:` header (compinit regenerating) gets the metadata re-appended, an invalid `$ZSH_COMPDUMP` path still starts cleanly. + +🤖 Co-authored with Claude Code + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `426650fbe894`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14061/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14061/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..24fcbf807439d0f9a147f080fdd3f91132555046 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14061/solution/patch.diff @@ -0,0 +1,44 @@ +diff --git a/oh-my-zsh.sh b/oh-my-zsh.sh +index b4e95e0f..661e2e10 100644 +--- a/oh-my-zsh.sh ++++ b/oh-my-zsh.sh +@@ -114,9 +114,17 @@ fi + zcompdump_revision="#omz revision: $(builtin cd -q "$ZSH"; git rev-parse HEAD 2>/dev/null)" + zcompdump_fpath="#omz fpath: $fpath" + ++# Check whether the zcompdump file carries the current OMZ metadata lines ++_omz_compdump_has_metadata() { ++ local -a lines ++ [[ -r "$ZSH_COMPDUMP" ]] || return 1 ++ lines=("${(@f)$(<"$ZSH_COMPDUMP")}") ++ (( ${lines[(Ie)$zcompdump_revision]} && ${lines[(Ie)$zcompdump_fpath]} )) ++} ++ + # Delete the zcompdump file if OMZ zcompdump metadata changed +-if ! command grep -q -Fx "$zcompdump_revision" "$ZSH_COMPDUMP" 2>/dev/null \ +- || ! command grep -q -Fx "$zcompdump_fpath" "$ZSH_COMPDUMP" 2>/dev/null; then ++zcompdump_refresh=0 ++if ! _omz_compdump_has_metadata; then + command rm -f "$ZSH_COMPDUMP" + zcompdump_refresh=1 + fi +@@ -134,9 +142,8 @@ else + compinit -u -d "$ZSH_COMPDUMP" + fi + +-# Append zcompdump metadata if missing +-if (( $zcompdump_refresh )) \ +- || ! command grep -q -Fx "$zcompdump_revision" "$ZSH_COMPDUMP" 2>/dev/null; then ++# Append zcompdump metadata if missing (compinit may have regenerated the file) ++if (( zcompdump_refresh )) || ! _omz_compdump_has_metadata; then + # Use `tee` in case the $ZSH_COMPDUMP filename is invalid, to silence the error + # See https://github.com/ohmyzsh/ohmyzsh/commit/dd1a7269#commitcomment-39003489 + tee -a "$ZSH_COMPDUMP" &>/dev/null </dev/null; then diff --git a/tasks/ohmyzsh__ohmyzsh-14061/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14061/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14061/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14061/task.toml b/tasks/ohmyzsh__ohmyzsh-14061/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bfd1f23aa2dc327ce1c5abcc61ad2fb0ed0ce3d2 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14061/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14061" +description = "perf(init): check zcompdump metadata without forking grep" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "426650fbe8943879af72703556ae5d1eb2eac734" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14061" +source_access = "auto" +built_at = "2026-11-16T16:09:56.990274+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:954add705d3da0b94a1f4c7777a6d24c634fe6a17add2ea183111077f61ddc61" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-07T08:18:49Z" +diff_format = "unified" +context_files = [ + "oh-my-zsh.sh", +] +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.980769+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3f5f1ee28d2ad917c2a988746b3228307fc5d51980b9e3d4004db674cd2dce87" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14061/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14061/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14061/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14061/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14061/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ba501360adb6f7ec9195cbab440190a5ecf202ff --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14061/tests/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** perf(init): check zcompdump metadata without forking grep + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- The zcompdump metadata lines (`#omz revision:` and `#omz fpath:`) were checked with two `grep -Fx` runs over the whole dump on every startup, plus a third grep after `compinit`. +- Read the dump once in zsh and test membership with `(Ie)` instead. The check after `compinit` is kept, since `compinit` can regenerate the dump and drop the metadata. +- No behaviour change: the dump is still deleted when the revision or `$fpath` changes, and the metadata is still appended when missing. + +## Other comments: + +First of a series of small startup-time PRs. Profiled with an isolated `ZDOTDIR` on macOS arm64, zsh 5.9, default template, warm dump: this step takes the metadata check + append from 17.5 ms to 3.3 ms per interactive start. Roughly 80% of what Oh My Zsh itself adds to a warm startup is process forks plus `compaudit`, so each PR in the series removes one fork. + +Verified: cold start regenerates the dump with metadata, changing `plugins=()` regenerates it, a stale `#files:` header (compinit regenerating) gets the metadata re-appended, an invalid `$ZSH_COMPDUMP` path still starts cleanly. + +🤖 Co-authored with Claude Code + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `426650fbe894`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14061/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14061/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..24fcbf807439d0f9a147f080fdd3f91132555046 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14061/tests/oracle.patch @@ -0,0 +1,44 @@ +diff --git a/oh-my-zsh.sh b/oh-my-zsh.sh +index b4e95e0f..661e2e10 100644 +--- a/oh-my-zsh.sh ++++ b/oh-my-zsh.sh +@@ -114,9 +114,17 @@ fi + zcompdump_revision="#omz revision: $(builtin cd -q "$ZSH"; git rev-parse HEAD 2>/dev/null)" + zcompdump_fpath="#omz fpath: $fpath" + ++# Check whether the zcompdump file carries the current OMZ metadata lines ++_omz_compdump_has_metadata() { ++ local -a lines ++ [[ -r "$ZSH_COMPDUMP" ]] || return 1 ++ lines=("${(@f)$(<"$ZSH_COMPDUMP")}") ++ (( ${lines[(Ie)$zcompdump_revision]} && ${lines[(Ie)$zcompdump_fpath]} )) ++} ++ + # Delete the zcompdump file if OMZ zcompdump metadata changed +-if ! command grep -q -Fx "$zcompdump_revision" "$ZSH_COMPDUMP" 2>/dev/null \ +- || ! command grep -q -Fx "$zcompdump_fpath" "$ZSH_COMPDUMP" 2>/dev/null; then ++zcompdump_refresh=0 ++if ! _omz_compdump_has_metadata; then + command rm -f "$ZSH_COMPDUMP" + zcompdump_refresh=1 + fi +@@ -134,9 +142,8 @@ else + compinit -u -d "$ZSH_COMPDUMP" + fi + +-# Append zcompdump metadata if missing +-if (( $zcompdump_refresh )) \ +- || ! command grep -q -Fx "$zcompdump_revision" "$ZSH_COMPDUMP" 2>/dev/null; then ++# Append zcompdump metadata if missing (compinit may have regenerated the file) ++if (( zcompdump_refresh )) || ! _omz_compdump_has_metadata; then + # Use `tee` in case the $ZSH_COMPDUMP filename is invalid, to silence the error + # See https://github.com/ohmyzsh/ohmyzsh/commit/dd1a7269#commitcomment-39003489 + tee -a "$ZSH_COMPDUMP" &>/dev/null </dev/null; then diff --git a/tasks/ohmyzsh__ohmyzsh-14061/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14061/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d3066340b1c376424520d4eb788de7b3332052a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14061/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 426650fbe8943879af72703556ae5d1eb2eac734 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14061/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14061/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14061/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14062/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14062/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7f85d14cf0ec2432431ce51881570fbac46b8bf6 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14062/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 426650fbe8943879af72703556ae5d1eb2eac734 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 426650fbe8943879af72703556ae5d1eb2eac734 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 426650fbe8943879af72703556ae5d1eb2eac734 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14062/instruction.md b/tasks/ohmyzsh__ohmyzsh-14062/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1a365c3029f5f5552a24feaf6d2f9d791d706a55 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14062/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** perf(update): check the update epoch before forking git + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- With the default `prompt` update mode, every interactive shell on a tty ran `git --version`, `git rev-parse --is-inside-work-tree`, `mkdir` for the lock directory and `rm -rf` to remove it, only to find out that the update frequency hadn't elapsed yet. +- Read `.zsh-update` and compare the epoch first, and only fall through to the git and lock handling when a check is actually due. +- The shortcut is skipped when a background update left an `EXIT_STATUS` to report, so `background-alpha` mode still shows its result on the next prompt. + +## Other comments: + +Part of a series of small startup-time PRs. Measured on macOS arm64, zsh 5.9, on a pty with a fresh `LAST_EPOCH`: `check_for_upgrade.sh` goes from 27 ms to 1.6 ms, 4 forks to 0. + +Verified on a pty: fresh `LAST_EPOCH` returns early with no forks; a `LAST_EPOCH` 100 days old takes the full path and rewrites the file; `background-alpha` with a pending `EXIT_STATUS` still registers its precmd hook; a missing or malformed `.zsh-update` is recreated as before. No globals leak from the early check. + +🤖 Co-authored with Claude Code + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `426650fbe894`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14062/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14062/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..bdf5fbff2bb2624435af648d6966d5f326488f6e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14062/solution/patch.diff @@ -0,0 +1,41 @@ +diff --git a/tools/check_for_upgrade.sh b/tools/check_for_upgrade.sh +index f19ce4c1..6f3ed506 100644 +--- a/tools/check_for_upgrade.sh ++++ b/tools/check_for_upgrade.sh +@@ -23,12 +23,32 @@ zstyle -s ':omz:update' mode update_mode || { + # - the automatic update is disabled + # - the current user doesn't have write permissions nor owns the $ZSH directory + # - is not run from a tty +-# - git is unavailable on the system +-# - $ZSH is not a git repository + if [[ "$update_mode" = disabled ]] \ + || [[ ! -w "$ZSH" || ! -O "$ZSH" ]] \ +- || [[ ! -t 1 && ${POWERLEVEL9K_INSTANT_PROMPT:-off} == off ]] \ +- || ! command git --version >/dev/null 2>&1 \ ++ || [[ ! -t 1 && ${POWERLEVEL9K_INSTANT_PROMPT:-off} == off ]]; then ++ unset update_mode ++ return ++fi ++ ++# Cancel update if it's not time to check yet. This runs before the git checks ++# below because those fork on every startup. Skipped when a background update ++# left a result that still needs to be reported (EXIT_STATUS is set). ++() { ++ local LAST_EPOCH EXIT_STATUS ERROR epoch_target ++ zmodload zsh/datetime ++ source "${ZSH_CACHE_DIR}/.zsh-update" 2>/dev/null || return 1 ++ [[ -n "$LAST_EPOCH" && -z "$EXIT_STATUS" ]] || return 1 ++ zstyle -s ':omz:update' frequency epoch_target || epoch_target=${UPDATE_ZSH_DAYS:-13} ++ (( ( EPOCHSECONDS / 60 / 60 / 24 - LAST_EPOCH ) < epoch_target )) ++} && { ++ unset update_mode ++ return ++} ++ ++# Cancel update if: ++# - git is unavailable on the system ++# - $ZSH is not a git repository ++if ! command git --version >/dev/null 2>&1 \ + || (builtin cd -q "$ZSH"; ! command git rev-parse --is-inside-work-tree &>/dev/null); then + unset update_mode + return diff --git a/tasks/ohmyzsh__ohmyzsh-14062/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14062/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14062/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14062/task.toml b/tasks/ohmyzsh__ohmyzsh-14062/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..159c96cf0bf50050a7999f5548a27ff1c3279199 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14062/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14062" +description = "perf(update): check the update epoch before forking git" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "426650fbe8943879af72703556ae5d1eb2eac734" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14062" +source_access = "auto" +built_at = "2026-11-16T16:09:56.991979+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b51e0b20628f1f5e7311a7e94a6d2c654f770b785a11e2c30bbab6975ad0b97e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-07T08:17:25Z" +diff_format = "unified" +context_files = [ + "tools/check_for_upgrade.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 28 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.981282+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3f5f1ee28d2ad917c2a988746b3228307fc5d51980b9e3d4004db674cd2dce87" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14062/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14062/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14062/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14062/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14062/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1a365c3029f5f5552a24feaf6d2f9d791d706a55 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14062/tests/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** perf(update): check the update epoch before forking git + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- With the default `prompt` update mode, every interactive shell on a tty ran `git --version`, `git rev-parse --is-inside-work-tree`, `mkdir` for the lock directory and `rm -rf` to remove it, only to find out that the update frequency hadn't elapsed yet. +- Read `.zsh-update` and compare the epoch first, and only fall through to the git and lock handling when a check is actually due. +- The shortcut is skipped when a background update left an `EXIT_STATUS` to report, so `background-alpha` mode still shows its result on the next prompt. + +## Other comments: + +Part of a series of small startup-time PRs. Measured on macOS arm64, zsh 5.9, on a pty with a fresh `LAST_EPOCH`: `check_for_upgrade.sh` goes from 27 ms to 1.6 ms, 4 forks to 0. + +Verified on a pty: fresh `LAST_EPOCH` returns early with no forks; a `LAST_EPOCH` 100 days old takes the full path and rewrites the file; `background-alpha` with a pending `EXIT_STATUS` still registers its precmd hook; a missing or malformed `.zsh-update` is recreated as before. No globals leak from the early check. + +🤖 Co-authored with Claude Code + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `426650fbe894`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14062/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14062/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..bdf5fbff2bb2624435af648d6966d5f326488f6e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14062/tests/oracle.patch @@ -0,0 +1,41 @@ +diff --git a/tools/check_for_upgrade.sh b/tools/check_for_upgrade.sh +index f19ce4c1..6f3ed506 100644 +--- a/tools/check_for_upgrade.sh ++++ b/tools/check_for_upgrade.sh +@@ -23,12 +23,32 @@ zstyle -s ':omz:update' mode update_mode || { + # - the automatic update is disabled + # - the current user doesn't have write permissions nor owns the $ZSH directory + # - is not run from a tty +-# - git is unavailable on the system +-# - $ZSH is not a git repository + if [[ "$update_mode" = disabled ]] \ + || [[ ! -w "$ZSH" || ! -O "$ZSH" ]] \ +- || [[ ! -t 1 && ${POWERLEVEL9K_INSTANT_PROMPT:-off} == off ]] \ +- || ! command git --version >/dev/null 2>&1 \ ++ || [[ ! -t 1 && ${POWERLEVEL9K_INSTANT_PROMPT:-off} == off ]]; then ++ unset update_mode ++ return ++fi ++ ++# Cancel update if it's not time to check yet. This runs before the git checks ++# below because those fork on every startup. Skipped when a background update ++# left a result that still needs to be reported (EXIT_STATUS is set). ++() { ++ local LAST_EPOCH EXIT_STATUS ERROR epoch_target ++ zmodload zsh/datetime ++ source "${ZSH_CACHE_DIR}/.zsh-update" 2>/dev/null || return 1 ++ [[ -n "$LAST_EPOCH" && -z "$EXIT_STATUS" ]] || return 1 ++ zstyle -s ':omz:update' frequency epoch_target || epoch_target=${UPDATE_ZSH_DAYS:-13} ++ (( ( EPOCHSECONDS / 60 / 60 / 24 - LAST_EPOCH ) < epoch_target )) ++} && { ++ unset update_mode ++ return ++} ++ ++# Cancel update if: ++# - git is unavailable on the system ++# - $ZSH is not a git repository ++if ! command git --version >/dev/null 2>&1 \ + || (builtin cd -q "$ZSH"; ! command git rev-parse --is-inside-work-tree &>/dev/null); then + unset update_mode + return diff --git a/tasks/ohmyzsh__ohmyzsh-14062/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14062/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d3066340b1c376424520d4eb788de7b3332052a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14062/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 426650fbe8943879af72703556ae5d1eb2eac734 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14062/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14062/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14062/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14063/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14063/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7f85d14cf0ec2432431ce51881570fbac46b8bf6 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14063/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 426650fbe8943879af72703556ae5d1eb2eac734 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 426650fbe8943879af72703556ae5d1eb2eac734 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 426650fbe8943879af72703556ae5d1eb2eac734 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14063/instruction.md b/tasks/ohmyzsh__ohmyzsh-14063/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5ed334fc562e94fcb3e75ad1f14706578b103112 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14063/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** perf(init): read the OMZ revision from .git instead of forking + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- `git rev-parse HEAD` was forked on every startup only to stamp the zcompdump metadata with the OMZ revision. +- Resolve HEAD by reading the git directory in zsh: `.git` files (worktrees, submodules), worktree common dirs, detached HEADs and packed refs are handled. +- Falls back to `git rev-parse HEAD` whenever anything looks unexpected, so the worst case is the current behaviour. + +## Other comments: + +Part of a series of small startup-time PRs. Measured on macOS arm64, zsh 5.9: 7.4 ms to 0.2 ms per interactive start. The dump's `#omz revision:` line is identical to what `git rev-parse HEAD` prints. + +Verified against synthetic git dirs: loose ref, packed ref (and not matching a longer ref name like `master2`), detached HEAD, worktree via `.git` file + `commondir`, missing ref with no `packed-refs`, no `.git` at all, dangling `.git` file. The last three return non-zero and take the git fallback; an OMZ install that isn't a git checkout ends up with an empty revision, as today. + +🤖 Co-authored with Claude Code + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `426650fbe894`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14063/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14063/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1a9bdafac43e304e0a0c9f1d2188b930568f7ef1 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14063/solution/patch.diff @@ -0,0 +1,96 @@ +diff --git a/oh-my-zsh.sh b/oh-my-zsh.sh +index b4e95e0f..b9ccebe8 100644 +--- a/oh-my-zsh.sh ++++ b/oh-my-zsh.sh +@@ -110,9 +110,89 @@ if [[ -z "$ZSH_COMPDUMP" ]]; then + ZSH_COMPDUMP="${ZDOTDIR:-$HOME}/.zcompdump-${SHORT_HOST}-${ZSH_VERSION}" + fi + +-# Construct zcompdump OMZ metadata +-zcompdump_revision="#omz revision: $(builtin cd -q "$ZSH"; git rev-parse HEAD 2>/dev/null)" ++# Resolve the commit $ZSH is checked out at into $REPLY by reading the git ++# directory, so that no git process is forked on every startup. ++# Handles .git files (worktrees, submodules), worktree common dirs, detached ++# HEADs and packed refs. Returns 1 if anything is unexpected. ++_omz_git_head() { ++ local gitdir="$ZSH/.git" common head ref ++ local -a lines ++ REPLY= ++ ++ # .git may be a file pointing at the real git dir ++ if [[ -f "$gitdir" ]]; then ++ read -r head 2>/dev/null < "$gitdir" || return 1 ++ [[ "$head" = "gitdir: "* ]] || return 1 ++ gitdir="${head#gitdir: }" ++ [[ -n "$gitdir" ]] || return 1 ++ [[ "$gitdir" = /* ]] || gitdir="$ZSH/$gitdir" ++ fi ++ ++ # worktrees keep their refs in the common git dir ++ common="$gitdir" ++ if [[ -f "$gitdir/commondir" ]]; then ++ read -r common 2>/dev/null < "$gitdir/commondir" || return 1 ++ [[ "$common" = /* ]] || common="$gitdir/$common" ++ fi ++ ++ [[ -r "$gitdir/HEAD" ]] || return 1 ++ read -r head 2>/dev/null < "$gitdir/HEAD" || return 1 ++ ++ if [[ "$head" = ref:\ * ]]; then ++ ref="${head#ref: }" ++ ++ # Only use well-formed full ref names as paths. Besides matching Git's ref ++ # rules, this prevents a malformed HEAD from escaping the git directory. ++ [[ "$ref" = refs/?* \ ++ && "$ref" != *..* \ ++ && "$ref" != *//* \ ++ && "$ref" != */ \ ++ && "$ref" != */.* \ ++ && "$ref" != *.lock \ ++ && "$ref" != *.lock/* \ ++ && "$ref" != *. \ ++ && "$ref" != *'@{'* \ ++ && "$ref" != *[[:cntrl:]\ \~\^\:\?\*\[\\]* \ ++ ]] || return 1 ++ ++ case "$ref" in ++ # These namespaces are private to each worktree and are never resolved ++ # from the common directory or its packed-refs file. ++ refs/bisect/*|refs/worktree/*|refs/rewritten/*) ++ [[ -r "$gitdir/$ref" ]] || return 1 ++ read -r REPLY 2>/dev/null < "$gitdir/$ref" || return 1 ++ ;; ++ *) ++ if [[ -r "$common/$ref" ]]; then ++ read -r REPLY 2>/dev/null < "$common/$ref" || return 1 ++ elif [[ -r "$common/packed-refs" ]]; then ++ lines=("${(@f)$(<"$common/packed-refs")}") ++ REPLY="${lines[(r)* ${(b)ref}]%% *}" ++ else ++ return 1 ++ fi ++ ;; ++ esac ++ else ++ # detached HEAD: the file holds the commit itself ++ REPLY="$head" ++ fi ++ ++ # only an object ID is a usable answer: a symbolic ref, a malformed file or ++ # a missed packed entry all fall through to the git fallback instead ++ [[ -n "$REPLY" && -z "${REPLY//[0-9a-f]/}" ]] \ ++ && (( ${#REPLY} == 40 || ${#REPLY} == 64 )) ++} ++ ++# Construct zcompdump OMZ metadata. The helper reports through $REPLY, so ++# call it in a scope that keeps that out of the global namespace. ++() { ++ local REPLY ++ _omz_git_head || REPLY="$(builtin cd -q "$ZSH"; git rev-parse HEAD 2>/dev/null)" ++ typeset -g zcompdump_revision="#omz revision: $REPLY" ++} + zcompdump_fpath="#omz fpath: $fpath" ++unset -f _omz_git_head + + # Delete the zcompdump file if OMZ zcompdump metadata changed + if ! command grep -q -Fx "$zcompdump_revision" "$ZSH_COMPDUMP" 2>/dev/null \ diff --git a/tasks/ohmyzsh__ohmyzsh-14063/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14063/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14063/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14063/task.toml b/tasks/ohmyzsh__ohmyzsh-14063/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e0922a69eb00e4ee83cc4d0c0f3373fd068ce69d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14063/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14063" +description = "perf(init): read the OMZ revision from .git instead of forking" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "426650fbe8943879af72703556ae5d1eb2eac734" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14063" +source_access = "auto" +built_at = "2026-11-16T16:09:56.920290+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d4d08ca27e9597aa401966a9f357f53decf1ace458e8dbd03de1eb4c7103da92" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-22T15:46:16Z" +diff_format = "unified" +context_files = [ + "oh-my-zsh.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 84 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.981817+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3f5f1ee28d2ad917c2a988746b3228307fc5d51980b9e3d4004db674cd2dce87" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14063/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14063/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14063/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14063/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14063/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5ed334fc562e94fcb3e75ad1f14706578b103112 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14063/tests/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** perf(init): read the OMZ revision from .git instead of forking + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- `git rev-parse HEAD` was forked on every startup only to stamp the zcompdump metadata with the OMZ revision. +- Resolve HEAD by reading the git directory in zsh: `.git` files (worktrees, submodules), worktree common dirs, detached HEADs and packed refs are handled. +- Falls back to `git rev-parse HEAD` whenever anything looks unexpected, so the worst case is the current behaviour. + +## Other comments: + +Part of a series of small startup-time PRs. Measured on macOS arm64, zsh 5.9: 7.4 ms to 0.2 ms per interactive start. The dump's `#omz revision:` line is identical to what `git rev-parse HEAD` prints. + +Verified against synthetic git dirs: loose ref, packed ref (and not matching a longer ref name like `master2`), detached HEAD, worktree via `.git` file + `commondir`, missing ref with no `packed-refs`, no `.git` at all, dangling `.git` file. The last three return non-zero and take the git fallback; an OMZ install that isn't a git checkout ends up with an empty revision, as today. + +🤖 Co-authored with Claude Code + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `426650fbe894`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14063/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14063/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1a9bdafac43e304e0a0c9f1d2188b930568f7ef1 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14063/tests/oracle.patch @@ -0,0 +1,96 @@ +diff --git a/oh-my-zsh.sh b/oh-my-zsh.sh +index b4e95e0f..b9ccebe8 100644 +--- a/oh-my-zsh.sh ++++ b/oh-my-zsh.sh +@@ -110,9 +110,89 @@ if [[ -z "$ZSH_COMPDUMP" ]]; then + ZSH_COMPDUMP="${ZDOTDIR:-$HOME}/.zcompdump-${SHORT_HOST}-${ZSH_VERSION}" + fi + +-# Construct zcompdump OMZ metadata +-zcompdump_revision="#omz revision: $(builtin cd -q "$ZSH"; git rev-parse HEAD 2>/dev/null)" ++# Resolve the commit $ZSH is checked out at into $REPLY by reading the git ++# directory, so that no git process is forked on every startup. ++# Handles .git files (worktrees, submodules), worktree common dirs, detached ++# HEADs and packed refs. Returns 1 if anything is unexpected. ++_omz_git_head() { ++ local gitdir="$ZSH/.git" common head ref ++ local -a lines ++ REPLY= ++ ++ # .git may be a file pointing at the real git dir ++ if [[ -f "$gitdir" ]]; then ++ read -r head 2>/dev/null < "$gitdir" || return 1 ++ [[ "$head" = "gitdir: "* ]] || return 1 ++ gitdir="${head#gitdir: }" ++ [[ -n "$gitdir" ]] || return 1 ++ [[ "$gitdir" = /* ]] || gitdir="$ZSH/$gitdir" ++ fi ++ ++ # worktrees keep their refs in the common git dir ++ common="$gitdir" ++ if [[ -f "$gitdir/commondir" ]]; then ++ read -r common 2>/dev/null < "$gitdir/commondir" || return 1 ++ [[ "$common" = /* ]] || common="$gitdir/$common" ++ fi ++ ++ [[ -r "$gitdir/HEAD" ]] || return 1 ++ read -r head 2>/dev/null < "$gitdir/HEAD" || return 1 ++ ++ if [[ "$head" = ref:\ * ]]; then ++ ref="${head#ref: }" ++ ++ # Only use well-formed full ref names as paths. Besides matching Git's ref ++ # rules, this prevents a malformed HEAD from escaping the git directory. ++ [[ "$ref" = refs/?* \ ++ && "$ref" != *..* \ ++ && "$ref" != *//* \ ++ && "$ref" != */ \ ++ && "$ref" != */.* \ ++ && "$ref" != *.lock \ ++ && "$ref" != *.lock/* \ ++ && "$ref" != *. \ ++ && "$ref" != *'@{'* \ ++ && "$ref" != *[[:cntrl:]\ \~\^\:\?\*\[\\]* \ ++ ]] || return 1 ++ ++ case "$ref" in ++ # These namespaces are private to each worktree and are never resolved ++ # from the common directory or its packed-refs file. ++ refs/bisect/*|refs/worktree/*|refs/rewritten/*) ++ [[ -r "$gitdir/$ref" ]] || return 1 ++ read -r REPLY 2>/dev/null < "$gitdir/$ref" || return 1 ++ ;; ++ *) ++ if [[ -r "$common/$ref" ]]; then ++ read -r REPLY 2>/dev/null < "$common/$ref" || return 1 ++ elif [[ -r "$common/packed-refs" ]]; then ++ lines=("${(@f)$(<"$common/packed-refs")}") ++ REPLY="${lines[(r)* ${(b)ref}]%% *}" ++ else ++ return 1 ++ fi ++ ;; ++ esac ++ else ++ # detached HEAD: the file holds the commit itself ++ REPLY="$head" ++ fi ++ ++ # only an object ID is a usable answer: a symbolic ref, a malformed file or ++ # a missed packed entry all fall through to the git fallback instead ++ [[ -n "$REPLY" && -z "${REPLY//[0-9a-f]/}" ]] \ ++ && (( ${#REPLY} == 40 || ${#REPLY} == 64 )) ++} ++ ++# Construct zcompdump OMZ metadata. The helper reports through $REPLY, so ++# call it in a scope that keeps that out of the global namespace. ++() { ++ local REPLY ++ _omz_git_head || REPLY="$(builtin cd -q "$ZSH"; git rev-parse HEAD 2>/dev/null)" ++ typeset -g zcompdump_revision="#omz revision: $REPLY" ++} + zcompdump_fpath="#omz fpath: $fpath" ++unset -f _omz_git_head + + # Delete the zcompdump file if OMZ zcompdump metadata changed + if ! command grep -q -Fx "$zcompdump_revision" "$ZSH_COMPDUMP" 2>/dev/null \ diff --git a/tasks/ohmyzsh__ohmyzsh-14063/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14063/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d3066340b1c376424520d4eb788de7b3332052a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14063/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 426650fbe8943879af72703556ae5d1eb2eac734 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14063/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14063/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14063/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14064/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14064/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7f85d14cf0ec2432431ce51881570fbac46b8bf6 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14064/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 426650fbe8943879af72703556ae5d1eb2eac734 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 426650fbe8943879af72703556ae5d1eb2eac734 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 426650fbe8943879af72703556ae5d1eb2eac734 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14064/instruction.md b/tasks/ohmyzsh__ohmyzsh-14064/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8cab8eaa7da9c36128ee3c442c841a44e060b042 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14064/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** perf(init): skip the compdump lock and zrecompile when the .zwc is fresh + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Every startup created the `${ZSH_COMPDUMP}.lock` directory, ran `zrecompile -p` (which forks `wc` even when there is nothing to do) and removed the lock again. +- Test whether the `.zwc` is already newer than the dump first, which is the same check `zrecompile -p` makes, and only take the lock when a recompile is due. + +## Other comments: + +Part of a series of small startup-time PRs. Measured on macOS arm64, zsh 5.9: 7.8 ms to 0.1 ms per interactive start. + +Verified: a missing `.zwc` is created; a dump newer than the `.zwc` gets it recompiled; a fresh `.zwc` is left untouched with no lock directory left behind; a cold start (no dump at all) creates both. + +🤖 Co-authored with Claude Code + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `426650fbe894`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14064/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14064/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e57396d917c9e34a967bdf5e0210296e115b207e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14064/solution/patch.diff @@ -0,0 +1,15 @@ +diff --git a/oh-my-zsh.sh b/oh-my-zsh.sh +index b4e95e0f..63e18edd 100644 +--- a/oh-my-zsh.sh ++++ b/oh-my-zsh.sh +@@ -148,7 +148,9 @@ fi + unset zcompdump_revision zcompdump_fpath zcompdump_refresh + + # zcompile the completion dump file if the .zwc is older or missing. +-if command mkdir "${ZSH_COMPDUMP}.lock" 2>/dev/null; then ++# Test that first so the lock directory and zrecompile are skipped when it's fresh. ++if [[ ! "${ZSH_COMPDUMP}.zwc" -nt "$ZSH_COMPDUMP" ]] \ ++ && command mkdir "${ZSH_COMPDUMP}.lock" 2>/dev/null; then + zrecompile -q -p "$ZSH_COMPDUMP" + command rm -rf "$ZSH_COMPDUMP.zwc.old" "${ZSH_COMPDUMP}.lock" + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14064/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14064/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14064/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14064/task.toml b/tasks/ohmyzsh__ohmyzsh-14064/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..52fd899f25925f3cc3a1da5661cb4019d8dd2d51 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14064/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14064" +description = "perf(init): skip the compdump lock and zrecompile when the .zwc is fresh" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "426650fbe8943879af72703556ae5d1eb2eac734" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14064" +source_access = "auto" +built_at = "2026-11-16T16:09:56.993707+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:4745b3582bcdaa39ddb7a87e0f48269ce7084b50732bf3a49d5b0367e7d0b295" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-07T08:14:57Z" +diff_format = "unified" +context_files = [ + "oh-my-zsh.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.982323+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3f5f1ee28d2ad917c2a988746b3228307fc5d51980b9e3d4004db674cd2dce87" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14064/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14064/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14064/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14064/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14064/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8cab8eaa7da9c36128ee3c442c841a44e060b042 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14064/tests/instruction.md @@ -0,0 +1,34 @@ +# Issue + +**Title:** perf(init): skip the compdump lock and zrecompile when the .zwc is fresh + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Every startup created the `${ZSH_COMPDUMP}.lock` directory, ran `zrecompile -p` (which forks `wc` even when there is nothing to do) and removed the lock again. +- Test whether the `.zwc` is already newer than the dump first, which is the same check `zrecompile -p` makes, and only take the lock when a recompile is due. + +## Other comments: + +Part of a series of small startup-time PRs. Measured on macOS arm64, zsh 5.9: 7.8 ms to 0.1 ms per interactive start. + +Verified: a missing `.zwc` is created; a dump newer than the `.zwc` gets it recompiled; a fresh `.zwc` is left untouched with no lock directory left behind; a cold start (no dump at all) creates both. + +🤖 Co-authored with Claude Code + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `426650fbe894`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14064/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14064/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e57396d917c9e34a967bdf5e0210296e115b207e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14064/tests/oracle.patch @@ -0,0 +1,15 @@ +diff --git a/oh-my-zsh.sh b/oh-my-zsh.sh +index b4e95e0f..63e18edd 100644 +--- a/oh-my-zsh.sh ++++ b/oh-my-zsh.sh +@@ -148,7 +148,9 @@ fi + unset zcompdump_revision zcompdump_fpath zcompdump_refresh + + # zcompile the completion dump file if the .zwc is older or missing. +-if command mkdir "${ZSH_COMPDUMP}.lock" 2>/dev/null; then ++# Test that first so the lock directory and zrecompile are skipped when it's fresh. ++if [[ ! "${ZSH_COMPDUMP}.zwc" -nt "$ZSH_COMPDUMP" ]] \ ++ && command mkdir "${ZSH_COMPDUMP}.lock" 2>/dev/null; then + zrecompile -q -p "$ZSH_COMPDUMP" + command rm -rf "$ZSH_COMPDUMP.zwc.old" "${ZSH_COMPDUMP}.lock" + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14064/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14064/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d3066340b1c376424520d4eb788de7b3332052a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14064/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 426650fbe8943879af72703556ae5d1eb2eac734 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14064/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14064/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14064/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14066/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14066/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7f85d14cf0ec2432431ce51881570fbac46b8bf6 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14066/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 426650fbe8943879af72703556ae5d1eb2eac734 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 426650fbe8943879af72703556ae5d1eb2eac734 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 426650fbe8943879af72703556ae5d1eb2eac734 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14066/instruction.md b/tasks/ohmyzsh__ohmyzsh-14066/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3c92e4d61e74f27d42cb91aeedda4979511adc9f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14066/instruction.md @@ -0,0 +1,37 @@ +# Issue + +**Title:** perf(init): cache the LocalHostName lookup + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- On macOS `scutil --get LocalHostName` was forked on every startup to get a stable short hostname for the zcompdump filename (#13171). +- The answer doesn't change from one shell to the next, so remember it in `$ZSH_CACHE_DIR/localhostname` against the `$HOST` it was looked up for, and only fork again when `$HOST` changes. +- A missing, empty or truncated cache file, or an unwritable `$ZSH_CACHE_DIR`, falls back to forking every time, which is today's behaviour. + +## Other comments: + +Part of a series of small startup-time PRs. Measured on macOS arm64, zsh 5.9: 5.9 ms on the first start, 0 ms on every start after that. + +The first version of this PR derived the short hostname from a `.local` suffix on `$HOST` instead of forking at all. Copilot pointed out that macOS lets `HostName` and `LocalHostName` be set independently, so someone with a `HostName` ending in `.local` would have got a different `SHORT_HOST` than before, and with it a different zcompdump name and different ssh-agent and keychain cache identities. `scutil` is the only authoritative source for `LocalHostName`, so this version keeps asking it and caches the answer rather than inferring one. + +Tested: a cold run forks once and gets the right name; every warm run forks zero times; a changed `$HOST` re-forks and gets the right name; and the missing, empty, truncated and unwritable-cache-dir cases all fall back to forking silently. The resulting compdump filename is unchanged on this machine (`.zcompdump--5.9`). + +🤖 Co-authored with Claude Code + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `426650fbe894`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14066/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14066/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7c34fffd49b2ad54cb06f6621e8ef84beaa41fbb --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14066/solution/patch.diff @@ -0,0 +1,34 @@ +diff --git a/oh-my-zsh.sh b/oh-my-zsh.sh +index b4e95e0f..8d53befc 100644 +--- a/oh-my-zsh.sh ++++ b/oh-my-zsh.sh +@@ -100,7 +100,28 @@ done + # Figure out the SHORT hostname + if [[ "$OSTYPE" = darwin* ]]; then + # macOS's $HOST changes with dhcp, etc. Use LocalHostName if possible. +- SHORT_HOST=$(scutil --get LocalHostName 2>/dev/null) || SHORT_HOST="${HOST/.*/}" ++ # scutil costs a fork on every start, so remember its answer for a day ++ # (like lib/grep.zsh) and re-check sooner if $HOST changes. ++ __omz_host_cache="$ZSH_CACHE_DIR/localhostname" ++ __omz_host_cached=("$__omz_host_cache"(Nm-1)) ++ __omz_host_key= ++ SHORT_HOST= ++ if [[ -n "$__omz_host_cached" ]]; then ++ if ! { read -r __omz_host_key && read -r SHORT_HOST } < "$__omz_host_cache"; then ++ __omz_host_key= ++ SHORT_HOST= ++ fi ++ fi ++ if [[ "$__omz_host_key" != "$HOST" || -z "$SHORT_HOST" ]]; then ++ # only cache what scutil actually answered, so a transient failure ++ # doesn't pin the fallback name for a day ++ if SHORT_HOST=$(scutil --get LocalHostName 2>/dev/null) && [[ -n "$SHORT_HOST" ]]; then ++ [[ ! -w "$ZSH_CACHE_DIR" ]] || print -rl -- "$HOST" "$SHORT_HOST" >| "$__omz_host_cache" ++ else ++ SHORT_HOST="${HOST/.*/}" ++ fi ++ fi ++ unset __omz_host_cache __omz_host_cached __omz_host_key + else + SHORT_HOST="${HOST/.*/}" + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14066/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14066/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14066/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14066/task.toml b/tasks/ohmyzsh__ohmyzsh-14066/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..90ea00afc7a86d7688f0228937b54e95b1ce10eb --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14066/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14066" +description = "perf(init): cache the LocalHostName lookup" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "426650fbe8943879af72703556ae5d1eb2eac734" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14066" +source_access = "auto" +built_at = "2026-11-16T16:09:56.931224+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6ec1fc8923e08e712f46fc89c453c8a5a3a16ff90c34d1a8ef868901ca7cbb4f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-18T09:27:07Z" +diff_format = "unified" +context_files = [ + "oh-my-zsh.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 23 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.982790+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3f5f1ee28d2ad917c2a988746b3228307fc5d51980b9e3d4004db674cd2dce87" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14066/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14066/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14066/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14066/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14066/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3c92e4d61e74f27d42cb91aeedda4979511adc9f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14066/tests/instruction.md @@ -0,0 +1,37 @@ +# Issue + +**Title:** perf(init): cache the LocalHostName lookup + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- On macOS `scutil --get LocalHostName` was forked on every startup to get a stable short hostname for the zcompdump filename (#13171). +- The answer doesn't change from one shell to the next, so remember it in `$ZSH_CACHE_DIR/localhostname` against the `$HOST` it was looked up for, and only fork again when `$HOST` changes. +- A missing, empty or truncated cache file, or an unwritable `$ZSH_CACHE_DIR`, falls back to forking every time, which is today's behaviour. + +## Other comments: + +Part of a series of small startup-time PRs. Measured on macOS arm64, zsh 5.9: 5.9 ms on the first start, 0 ms on every start after that. + +The first version of this PR derived the short hostname from a `.local` suffix on `$HOST` instead of forking at all. Copilot pointed out that macOS lets `HostName` and `LocalHostName` be set independently, so someone with a `HostName` ending in `.local` would have got a different `SHORT_HOST` than before, and with it a different zcompdump name and different ssh-agent and keychain cache identities. `scutil` is the only authoritative source for `LocalHostName`, so this version keeps asking it and caches the answer rather than inferring one. + +Tested: a cold run forks once and gets the right name; every warm run forks zero times; a changed `$HOST` re-forks and gets the right name; and the missing, empty, truncated and unwritable-cache-dir cases all fall back to forking silently. The resulting compdump filename is unchanged on this machine (`.zcompdump--5.9`). + +🤖 Co-authored with Claude Code + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `426650fbe894`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14066/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14066/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7c34fffd49b2ad54cb06f6621e8ef84beaa41fbb --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14066/tests/oracle.patch @@ -0,0 +1,34 @@ +diff --git a/oh-my-zsh.sh b/oh-my-zsh.sh +index b4e95e0f..8d53befc 100644 +--- a/oh-my-zsh.sh ++++ b/oh-my-zsh.sh +@@ -100,7 +100,28 @@ done + # Figure out the SHORT hostname + if [[ "$OSTYPE" = darwin* ]]; then + # macOS's $HOST changes with dhcp, etc. Use LocalHostName if possible. +- SHORT_HOST=$(scutil --get LocalHostName 2>/dev/null) || SHORT_HOST="${HOST/.*/}" ++ # scutil costs a fork on every start, so remember its answer for a day ++ # (like lib/grep.zsh) and re-check sooner if $HOST changes. ++ __omz_host_cache="$ZSH_CACHE_DIR/localhostname" ++ __omz_host_cached=("$__omz_host_cache"(Nm-1)) ++ __omz_host_key= ++ SHORT_HOST= ++ if [[ -n "$__omz_host_cached" ]]; then ++ if ! { read -r __omz_host_key && read -r SHORT_HOST } < "$__omz_host_cache"; then ++ __omz_host_key= ++ SHORT_HOST= ++ fi ++ fi ++ if [[ "$__omz_host_key" != "$HOST" || -z "$SHORT_HOST" ]]; then ++ # only cache what scutil actually answered, so a transient failure ++ # doesn't pin the fallback name for a day ++ if SHORT_HOST=$(scutil --get LocalHostName 2>/dev/null) && [[ -n "$SHORT_HOST" ]]; then ++ [[ ! -w "$ZSH_CACHE_DIR" ]] || print -rl -- "$HOST" "$SHORT_HOST" >| "$__omz_host_cache" ++ else ++ SHORT_HOST="${HOST/.*/}" ++ fi ++ fi ++ unset __omz_host_cache __omz_host_cached __omz_host_key + else + SHORT_HOST="${HOST/.*/}" + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14066/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14066/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d3066340b1c376424520d4eb788de7b3332052a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14066/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 426650fbe8943879af72703556ae5d1eb2eac734 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14066/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14066/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14066/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14067/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14067/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7f85d14cf0ec2432431ce51881570fbac46b8bf6 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14067/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 426650fbe8943879af72703556ae5d1eb2eac734 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 426650fbe8943879af72703556ae5d1eb2eac734 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 426650fbe8943879af72703556ae5d1eb2eac734 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14067/instruction.md b/tasks/ohmyzsh__ohmyzsh-14067/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..63e5f85975538cb4b10c5a5c5d898684bdd5d20b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14067/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** perf(appearance): cache the diff and ls capability probes + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- `diff --color` and `ls -G` (or `--color`, `gls`, `colorls` depending on the OS) were probed with a fork each on every startup. +- Remember the probe results in `$ZSH_CACHE_DIR/appearance-probes` for a day, the same way `lib/grep.zsh` caches its flag probe. `test-ls-args` becomes `test-cmd-args` and is used for the `diff` probe too. +- The ls section is wrapped in an anonymous function so the early return for `DISABLE_LS_COLORS` still runs the cleanup at the end of the file. Behaviour is otherwise unchanged. + +## Other comments: + +Part of a series of small startup-time PRs. Measured on macOS arm64, zsh 5.9: `lib/theme-and-appearance.zsh` goes from 5.7 ms to 0.7 ms per interactive start. + +Verified: first run writes the cache and sets `ls='ls -G'` plus the `diff` function; second run forks neither `diff` nor `ls` and gives the same result; a cache older than a day is re-probed; `DISABLE_LS_COLORS=true` sets no ls alias and no `LSCOLORS`, still wraps `diff`, and leaves no helper function or variable behind; the `gnu-ls` zstyle path probes `gls` and caches its absence. + +🤖 Co-authored with Claude Code + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `426650fbe894`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14067/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14067/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..803b49658c690cb6c0a4150cd1830b86558076fc --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14067/solution/patch.diff @@ -0,0 +1,151 @@ +diff --git a/lib/theme-and-appearance.zsh b/lib/theme-and-appearance.zsh +index 5cfa2e63..a5037e33 100644 +--- a/lib/theme-and-appearance.zsh ++++ b/lib/theme-and-appearance.zsh +@@ -13,69 +13,92 @@ ZSH_THEME_RUBY_PROMPT_PREFIX="(" + ZSH_THEME_RUBY_PROMPT_SUFFIX=")" + + ++# The command probes below fork a process each, and their result doesn't change ++# from one shell to the next, so they're cached for a day (like lib/grep.zsh). ++typeset -A __omz_probes ++__omz_probe_cache="$ZSH_CACHE_DIR/appearance-probes" ++__omz_probe_cached=("$__omz_probe_cache"(Nm-1)) ++[[ -z "$__omz_probe_cached" ]] || source "$__omz_probe_cache" ++ ++function __omz_test_cmd_args { ++ # Usage: __omz_test_cmd_args cmd args... ++ # Runs `cmd args... /dev/null` and remembers whether it succeeded, so a ++ # command needing two operands passes the first one itself: ++ # e.g. __omz_test_cmd_args gls --color -> gls --color /dev/null ++ # __omz_test_cmd_args diff --color /dev/null -> diff --color /dev/null /dev/null ++ local key="$*" ++ if (( ! ${+__omz_probes[$key]} )); then ++ command "$@" /dev/null &>/dev/null ++ __omz_probes[$key]=$? ++ if [[ -w "$ZSH_CACHE_DIR" ]]; then ++ print -r -- "__omz_probes=(" "${(@qqkv)__omz_probes}" ")" >| "$__omz_probe_cache" ++ fi ++ fi ++ return $__omz_probes[$key] ++} ++ + # Use diff --color if available +-if command diff --color /dev/null{,} &>/dev/null; then ++if __omz_test_cmd_args diff --color /dev/null; then + function diff { + command diff --color "$@" + } + fi + +-# Don't set ls coloring if disabled +-[[ "$DISABLE_LS_COLORS" != true ]] || return 0 ++# Set up ls coloring. Done in a function so the early return below still ++# reaches the cleanup at the end of this file. ++() { ++ # Don't set ls coloring if disabled ++ [[ "$DISABLE_LS_COLORS" != true ]] || return 0 + +-# Default coloring for BSD-based ls +-export LSCOLORS="Gxfxcxdxbxegedabagacad" ++ # Default coloring for BSD-based ls ++ export LSCOLORS="Gxfxcxdxbxegedabagacad" + +-# Default coloring for GNU-based ls +-if [[ -z "$LS_COLORS" ]]; then +- # Define LS_COLORS via dircolors if available. Otherwise, set a default +- # equivalent to LSCOLORS (generated via https://geoff.greer.fm/lscolors) +- if (( $+commands[dircolors] )); then +- [[ -f "$HOME/.dircolors" ]] \ +- && source <(dircolors -b "$HOME/.dircolors") \ +- || source <(dircolors -b) +- else +- export LS_COLORS="di=1;36:ln=35:so=32:pi=33:ex=31:bd=34;46:cd=34;43:su=30;41:sg=30;46:tw=30;42:ow=30;43" ++ # Default coloring for GNU-based ls ++ if [[ -z "$LS_COLORS" ]]; then ++ # Define LS_COLORS via dircolors if available. Otherwise, set a default ++ # equivalent to LSCOLORS (generated via https://geoff.greer.fm/lscolors) ++ if (( $+commands[dircolors] )); then ++ [[ -f "$HOME/.dircolors" ]] \ ++ && source <(dircolors -b "$HOME/.dircolors") \ ++ || source <(dircolors -b) ++ else ++ export LS_COLORS="di=1;36:ln=35:so=32:pi=33:ex=31:bd=34;46:cd=34;43:su=30;41:sg=30;46:tw=30;42:ow=30;43" ++ fi + fi +-fi + +-function test-ls-args { +- # Usage: test-ls-args cmd args... +- # e.g. test-ls-args gls --color +- command "$@" /dev/null &>/dev/null ++ # Find the option for using colors in ls, depending on the version ++ case "$OSTYPE" in ++ netbsd*) ++ # On NetBSD, test if `gls` (GNU ls) is installed (this one supports colors); ++ # otherwise, leave ls as is, because NetBSD's ls doesn't support -G ++ __omz_test_cmd_args gls --color && alias ls='gls --color=tty' ++ ;; ++ openbsd*) ++ # On OpenBSD, `gls` (ls from GNU coreutils) and `colorls` (ls from base, ++ # with color and multibyte support) are available from ports. ++ # `colorls` will be installed on purpose and can't be pulled in by installing ++ # coreutils (which might be installed for ), so prefer it to `gls`. ++ __omz_test_cmd_args gls --color && alias ls='gls --color=tty' ++ __omz_test_cmd_args colorls -G && alias ls='colorls -G' ++ ;; ++ (darwin|freebsd)*) ++ # This alias works by default just using $LSCOLORS ++ __omz_test_cmd_args ls -G && alias ls='ls -G' ++ # Only use GNU ls if installed and there are user defaults for $LS_COLORS, ++ # as the default coloring scheme is not very pretty ++ zstyle -t ':omz:lib:theme-and-appearance' gnu-ls \ ++ && __omz_test_cmd_args gls --color \ ++ && alias ls='gls --color=tty' ++ ;; ++ *) ++ if __omz_test_cmd_args ls --color; then ++ alias ls='ls --color=tty' ++ elif __omz_test_cmd_args ls -G; then ++ alias ls='ls -G' ++ fi ++ ;; ++ esac + } + +-# Find the option for using colors in ls, depending on the version +-case "$OSTYPE" in +- netbsd*) +- # On NetBSD, test if `gls` (GNU ls) is installed (this one supports colors); +- # otherwise, leave ls as is, because NetBSD's ls doesn't support -G +- test-ls-args gls --color && alias ls='gls --color=tty' +- ;; +- openbsd*) +- # On OpenBSD, `gls` (ls from GNU coreutils) and `colorls` (ls from base, +- # with color and multibyte support) are available from ports. +- # `colorls` will be installed on purpose and can't be pulled in by installing +- # coreutils (which might be installed for ), so prefer it to `gls`. +- test-ls-args gls --color && alias ls='gls --color=tty' +- test-ls-args colorls -G && alias ls='colorls -G' +- ;; +- (darwin|freebsd)*) +- # This alias works by default just using $LSCOLORS +- test-ls-args ls -G && alias ls='ls -G' +- # Only use GNU ls if installed and there are user defaults for $LS_COLORS, +- # as the default coloring scheme is not very pretty +- zstyle -t ':omz:lib:theme-and-appearance' gnu-ls \ +- && test-ls-args gls --color \ +- && alias ls='gls --color=tty' +- ;; +- *) +- if test-ls-args ls --color; then +- alias ls='ls --color=tty' +- elif test-ls-args ls -G; then +- alias ls='ls -G' +- fi +- ;; +-esac +- +-unfunction test-ls-args ++unfunction __omz_test_cmd_args ++unset __omz_probes __omz_probe_cache __omz_probe_cached diff --git a/tasks/ohmyzsh__ohmyzsh-14067/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14067/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14067/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14067/task.toml b/tasks/ohmyzsh__ohmyzsh-14067/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fb58fde2e7890471a0f058b91a9e43215ea8abd0 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14067/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14067" +description = "perf(appearance): cache the diff and ls capability probes" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "426650fbe8943879af72703556ae5d1eb2eac734" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14067" +source_access = "auto" +built_at = "2026-11-16T16:09:56.933115+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:7ce24ebedfc32ee52573c0b3627176eb44b6e2de426a3e2e9115db48250b7399" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-18T09:13:45Z" +diff_format = "unified" +context_files = [ + "lib/theme-and-appearance.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 131 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.983254+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3f5f1ee28d2ad917c2a988746b3228307fc5d51980b9e3d4004db674cd2dce87" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14067/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14067/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14067/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14067/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14067/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..63e5f85975538cb4b10c5a5c5d898684bdd5d20b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14067/tests/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** perf(appearance): cache the diff and ls capability probes + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- `diff --color` and `ls -G` (or `--color`, `gls`, `colorls` depending on the OS) were probed with a fork each on every startup. +- Remember the probe results in `$ZSH_CACHE_DIR/appearance-probes` for a day, the same way `lib/grep.zsh` caches its flag probe. `test-ls-args` becomes `test-cmd-args` and is used for the `diff` probe too. +- The ls section is wrapped in an anonymous function so the early return for `DISABLE_LS_COLORS` still runs the cleanup at the end of the file. Behaviour is otherwise unchanged. + +## Other comments: + +Part of a series of small startup-time PRs. Measured on macOS arm64, zsh 5.9: `lib/theme-and-appearance.zsh` goes from 5.7 ms to 0.7 ms per interactive start. + +Verified: first run writes the cache and sets `ls='ls -G'` plus the `diff` function; second run forks neither `diff` nor `ls` and gives the same result; a cache older than a day is re-probed; `DISABLE_LS_COLORS=true` sets no ls alias and no `LSCOLORS`, still wraps `diff`, and leaves no helper function or variable behind; the `gnu-ls` zstyle path probes `gls` and caches its absence. + +🤖 Co-authored with Claude Code + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `426650fbe894`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14067/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14067/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..803b49658c690cb6c0a4150cd1830b86558076fc --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14067/tests/oracle.patch @@ -0,0 +1,151 @@ +diff --git a/lib/theme-and-appearance.zsh b/lib/theme-and-appearance.zsh +index 5cfa2e63..a5037e33 100644 +--- a/lib/theme-and-appearance.zsh ++++ b/lib/theme-and-appearance.zsh +@@ -13,69 +13,92 @@ ZSH_THEME_RUBY_PROMPT_PREFIX="(" + ZSH_THEME_RUBY_PROMPT_SUFFIX=")" + + ++# The command probes below fork a process each, and their result doesn't change ++# from one shell to the next, so they're cached for a day (like lib/grep.zsh). ++typeset -A __omz_probes ++__omz_probe_cache="$ZSH_CACHE_DIR/appearance-probes" ++__omz_probe_cached=("$__omz_probe_cache"(Nm-1)) ++[[ -z "$__omz_probe_cached" ]] || source "$__omz_probe_cache" ++ ++function __omz_test_cmd_args { ++ # Usage: __omz_test_cmd_args cmd args... ++ # Runs `cmd args... /dev/null` and remembers whether it succeeded, so a ++ # command needing two operands passes the first one itself: ++ # e.g. __omz_test_cmd_args gls --color -> gls --color /dev/null ++ # __omz_test_cmd_args diff --color /dev/null -> diff --color /dev/null /dev/null ++ local key="$*" ++ if (( ! ${+__omz_probes[$key]} )); then ++ command "$@" /dev/null &>/dev/null ++ __omz_probes[$key]=$? ++ if [[ -w "$ZSH_CACHE_DIR" ]]; then ++ print -r -- "__omz_probes=(" "${(@qqkv)__omz_probes}" ")" >| "$__omz_probe_cache" ++ fi ++ fi ++ return $__omz_probes[$key] ++} ++ + # Use diff --color if available +-if command diff --color /dev/null{,} &>/dev/null; then ++if __omz_test_cmd_args diff --color /dev/null; then + function diff { + command diff --color "$@" + } + fi + +-# Don't set ls coloring if disabled +-[[ "$DISABLE_LS_COLORS" != true ]] || return 0 ++# Set up ls coloring. Done in a function so the early return below still ++# reaches the cleanup at the end of this file. ++() { ++ # Don't set ls coloring if disabled ++ [[ "$DISABLE_LS_COLORS" != true ]] || return 0 + +-# Default coloring for BSD-based ls +-export LSCOLORS="Gxfxcxdxbxegedabagacad" ++ # Default coloring for BSD-based ls ++ export LSCOLORS="Gxfxcxdxbxegedabagacad" + +-# Default coloring for GNU-based ls +-if [[ -z "$LS_COLORS" ]]; then +- # Define LS_COLORS via dircolors if available. Otherwise, set a default +- # equivalent to LSCOLORS (generated via https://geoff.greer.fm/lscolors) +- if (( $+commands[dircolors] )); then +- [[ -f "$HOME/.dircolors" ]] \ +- && source <(dircolors -b "$HOME/.dircolors") \ +- || source <(dircolors -b) +- else +- export LS_COLORS="di=1;36:ln=35:so=32:pi=33:ex=31:bd=34;46:cd=34;43:su=30;41:sg=30;46:tw=30;42:ow=30;43" ++ # Default coloring for GNU-based ls ++ if [[ -z "$LS_COLORS" ]]; then ++ # Define LS_COLORS via dircolors if available. Otherwise, set a default ++ # equivalent to LSCOLORS (generated via https://geoff.greer.fm/lscolors) ++ if (( $+commands[dircolors] )); then ++ [[ -f "$HOME/.dircolors" ]] \ ++ && source <(dircolors -b "$HOME/.dircolors") \ ++ || source <(dircolors -b) ++ else ++ export LS_COLORS="di=1;36:ln=35:so=32:pi=33:ex=31:bd=34;46:cd=34;43:su=30;41:sg=30;46:tw=30;42:ow=30;43" ++ fi + fi +-fi + +-function test-ls-args { +- # Usage: test-ls-args cmd args... +- # e.g. test-ls-args gls --color +- command "$@" /dev/null &>/dev/null ++ # Find the option for using colors in ls, depending on the version ++ case "$OSTYPE" in ++ netbsd*) ++ # On NetBSD, test if `gls` (GNU ls) is installed (this one supports colors); ++ # otherwise, leave ls as is, because NetBSD's ls doesn't support -G ++ __omz_test_cmd_args gls --color && alias ls='gls --color=tty' ++ ;; ++ openbsd*) ++ # On OpenBSD, `gls` (ls from GNU coreutils) and `colorls` (ls from base, ++ # with color and multibyte support) are available from ports. ++ # `colorls` will be installed on purpose and can't be pulled in by installing ++ # coreutils (which might be installed for ), so prefer it to `gls`. ++ __omz_test_cmd_args gls --color && alias ls='gls --color=tty' ++ __omz_test_cmd_args colorls -G && alias ls='colorls -G' ++ ;; ++ (darwin|freebsd)*) ++ # This alias works by default just using $LSCOLORS ++ __omz_test_cmd_args ls -G && alias ls='ls -G' ++ # Only use GNU ls if installed and there are user defaults for $LS_COLORS, ++ # as the default coloring scheme is not very pretty ++ zstyle -t ':omz:lib:theme-and-appearance' gnu-ls \ ++ && __omz_test_cmd_args gls --color \ ++ && alias ls='gls --color=tty' ++ ;; ++ *) ++ if __omz_test_cmd_args ls --color; then ++ alias ls='ls --color=tty' ++ elif __omz_test_cmd_args ls -G; then ++ alias ls='ls -G' ++ fi ++ ;; ++ esac + } + +-# Find the option for using colors in ls, depending on the version +-case "$OSTYPE" in +- netbsd*) +- # On NetBSD, test if `gls` (GNU ls) is installed (this one supports colors); +- # otherwise, leave ls as is, because NetBSD's ls doesn't support -G +- test-ls-args gls --color && alias ls='gls --color=tty' +- ;; +- openbsd*) +- # On OpenBSD, `gls` (ls from GNU coreutils) and `colorls` (ls from base, +- # with color and multibyte support) are available from ports. +- # `colorls` will be installed on purpose and can't be pulled in by installing +- # coreutils (which might be installed for ), so prefer it to `gls`. +- test-ls-args gls --color && alias ls='gls --color=tty' +- test-ls-args colorls -G && alias ls='colorls -G' +- ;; +- (darwin|freebsd)*) +- # This alias works by default just using $LSCOLORS +- test-ls-args ls -G && alias ls='ls -G' +- # Only use GNU ls if installed and there are user defaults for $LS_COLORS, +- # as the default coloring scheme is not very pretty +- zstyle -t ':omz:lib:theme-and-appearance' gnu-ls \ +- && test-ls-args gls --color \ +- && alias ls='gls --color=tty' +- ;; +- *) +- if test-ls-args ls --color; then +- alias ls='ls --color=tty' +- elif test-ls-args ls -G; then +- alias ls='ls -G' +- fi +- ;; +-esac +- +-unfunction test-ls-args ++unfunction __omz_test_cmd_args ++unset __omz_probes __omz_probe_cache __omz_probe_cached diff --git a/tasks/ohmyzsh__ohmyzsh-14067/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14067/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d3066340b1c376424520d4eb788de7b3332052a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14067/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 426650fbe8943879af72703556ae5d1eb2eac734 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14067/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14067/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14067/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14069/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14069/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7f85d14cf0ec2432431ce51881570fbac46b8bf6 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14069/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 426650fbe8943879af72703556ae5d1eb2eac734 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 426650fbe8943879af72703556ae5d1eb2eac734 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 426650fbe8943879af72703556ae5d1eb2eac734 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14069/instruction.md b/tasks/ohmyzsh__ohmyzsh-14069/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c7734b380172c7ee82a557c073b62f1cfbcefdb2 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14069/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** perf(git): fork git less often for the prompt + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- `_omz_git_prompt_info` ran `git rev-parse --git-dir` and then `git symbolic-ref --short HEAD` as two separate processes. Ask for both in one `git rev-parse --git-dir --abbrev-ref HEAD` call. A detached HEAD prints `HEAD` and falls through to the tag/SHA lookups as before; an unborn branch (exit 128 after printing the git dir) falls back to `symbolic-ref` so freshly initialised repositories still show their branch. +- `parse_git_dirty` piped `git status --porcelain` through `tail -n 1`, but only tests whether the output is empty, so the pipe is dropped. +- Two fewer forks per prompt. These run in the async worker, so this shortens the time until the git info appears rather than the time to first prompt. + +## Other comments: + +Part of a series of small startup-time PRs. Prompt output compared old vs new for: outside a repo, unborn, unborn with staged files, clean branch, dirty branch, detached, detached on a tag, `hide-info`, `hide-dirty`, a subdirectory, and this repo. All identical. About 13 ms less per prompt on a clean branch on macOS arm64. + +🤖 Co-authored with Claude Code + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `426650fbe894`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14069/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14069/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5c121e7efee4b57c94ca90bcf7e9f7eed90d937c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14069/solution/patch.diff @@ -0,0 +1,56 @@ +diff --git a/lib/git.zsh b/lib/git.zsh +index 41d01f66..8d56aba0 100644 +--- a/lib/git.zsh ++++ b/lib/git.zsh +@@ -12,10 +12,16 @@ function __git_prompt_git() { + } + + function _omz_git_prompt_info() { +- # If we are on a folder not tracked by git, get out. +- # Otherwise, check for hide-info at global and local repository level +- if ! __git_prompt_git rev-parse --git-dir &> /dev/null \ +- || [[ "$(__git_prompt_git config --get oh-my-zsh.hide-info 2>/dev/null)" == 1 ]]; then ++ # Get the git dir and the current branch name in one call. Outside a repo ++ # there is no output. On a detached HEAD the branch is "HEAD". On an unborn ++ # branch git exits non-zero after printing the git dir. ++ local -a info ++ info=("${(@f)$(__git_prompt_git rev-parse --git-dir --abbrev-ref HEAD 2> /dev/null)}") ++ local unborn=$(( $? != 0 )) ++ [[ -n "$info[1]" ]] || return 0 ++ ++ # Check for hide-info at global and local repository level ++ if [[ "$(__git_prompt_git config --get oh-my-zsh.hide-info 2>/dev/null)" == 1 ]]; then + return 0 + fi + +@@ -23,11 +29,15 @@ function _omz_git_prompt_info() { + # - the current branch name + # - the tag name if we are on a tag + # - the short SHA of the current commit +- local ref +- ref=$(__git_prompt_git symbolic-ref --short HEAD 2> /dev/null) \ +- || ref=$(__git_prompt_git describe --tags --exact-match HEAD 2> /dev/null) \ +- || ref=$(__git_prompt_git rev-parse --short HEAD 2> /dev/null) \ +- || return 0 ++ # a git dir path may contain newlines, so the branch is the last line ++ local ref="$info[-1]" ++ if (( unborn )); then ++ ref=$(__git_prompt_git symbolic-ref --short HEAD 2> /dev/null) || return 0 ++ elif [[ "$ref" == HEAD ]]; then ++ ref=$(__git_prompt_git describe --tags --exact-match HEAD 2> /dev/null) \ ++ || ref=$(__git_prompt_git rev-parse --short HEAD 2> /dev/null) \ ++ || return 0 ++ fi + + # Use global ZSH_THEME_GIT_SHOW_UPSTREAM=1 for including upstream remote info + local upstream +@@ -244,7 +254,8 @@ function parse_git_dirty() { + FLAGS+="--ignore-submodules=${GIT_STATUS_IGNORE_SUBMODULES:-dirty}" + ;; + esac +- STATUS=$(__git_prompt_git status ${FLAGS} 2> /dev/null | tail -n 1) ++ # only non-emptiness matters, so keep one line instead of the whole list ++ __git_prompt_git status ${FLAGS} 2> /dev/null | read -r STATUS + fi + if [[ -n $STATUS ]]; then + echo "$ZSH_THEME_GIT_PROMPT_DIRTY" diff --git a/tasks/ohmyzsh__ohmyzsh-14069/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14069/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14069/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14069/task.toml b/tasks/ohmyzsh__ohmyzsh-14069/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2f273478a0104202764bc374acd4d6c8f36e2af9 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14069/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14069" +description = "perf(git): fork git less often for the prompt" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "426650fbe8943879af72703556ae5d1eb2eac734" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14069" +source_access = "auto" +built_at = "2026-11-16T16:09:56.947993+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:57ccdfed2d84847a4d4062c544122576bd35bf7e654da55729509a2b28be98b8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-14T19:43:51Z" +diff_format = "unified" +context_files = [ + "lib/git.zsh", +] +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.983779+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3f5f1ee28d2ad917c2a988746b3228307fc5d51980b9e3d4004db674cd2dce87" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14069/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14069/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14069/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14069/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14069/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c7734b380172c7ee82a557c073b62f1cfbcefdb2 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14069/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** perf(git): fork git less often for the prompt + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- `_omz_git_prompt_info` ran `git rev-parse --git-dir` and then `git symbolic-ref --short HEAD` as two separate processes. Ask for both in one `git rev-parse --git-dir --abbrev-ref HEAD` call. A detached HEAD prints `HEAD` and falls through to the tag/SHA lookups as before; an unborn branch (exit 128 after printing the git dir) falls back to `symbolic-ref` so freshly initialised repositories still show their branch. +- `parse_git_dirty` piped `git status --porcelain` through `tail -n 1`, but only tests whether the output is empty, so the pipe is dropped. +- Two fewer forks per prompt. These run in the async worker, so this shortens the time until the git info appears rather than the time to first prompt. + +## Other comments: + +Part of a series of small startup-time PRs. Prompt output compared old vs new for: outside a repo, unborn, unborn with staged files, clean branch, dirty branch, detached, detached on a tag, `hide-info`, `hide-dirty`, a subdirectory, and this repo. All identical. About 13 ms less per prompt on a clean branch on macOS arm64. + +🤖 Co-authored with Claude Code + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `426650fbe894`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14069/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14069/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5c121e7efee4b57c94ca90bcf7e9f7eed90d937c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14069/tests/oracle.patch @@ -0,0 +1,56 @@ +diff --git a/lib/git.zsh b/lib/git.zsh +index 41d01f66..8d56aba0 100644 +--- a/lib/git.zsh ++++ b/lib/git.zsh +@@ -12,10 +12,16 @@ function __git_prompt_git() { + } + + function _omz_git_prompt_info() { +- # If we are on a folder not tracked by git, get out. +- # Otherwise, check for hide-info at global and local repository level +- if ! __git_prompt_git rev-parse --git-dir &> /dev/null \ +- || [[ "$(__git_prompt_git config --get oh-my-zsh.hide-info 2>/dev/null)" == 1 ]]; then ++ # Get the git dir and the current branch name in one call. Outside a repo ++ # there is no output. On a detached HEAD the branch is "HEAD". On an unborn ++ # branch git exits non-zero after printing the git dir. ++ local -a info ++ info=("${(@f)$(__git_prompt_git rev-parse --git-dir --abbrev-ref HEAD 2> /dev/null)}") ++ local unborn=$(( $? != 0 )) ++ [[ -n "$info[1]" ]] || return 0 ++ ++ # Check for hide-info at global and local repository level ++ if [[ "$(__git_prompt_git config --get oh-my-zsh.hide-info 2>/dev/null)" == 1 ]]; then + return 0 + fi + +@@ -23,11 +29,15 @@ function _omz_git_prompt_info() { + # - the current branch name + # - the tag name if we are on a tag + # - the short SHA of the current commit +- local ref +- ref=$(__git_prompt_git symbolic-ref --short HEAD 2> /dev/null) \ +- || ref=$(__git_prompt_git describe --tags --exact-match HEAD 2> /dev/null) \ +- || ref=$(__git_prompt_git rev-parse --short HEAD 2> /dev/null) \ +- || return 0 ++ # a git dir path may contain newlines, so the branch is the last line ++ local ref="$info[-1]" ++ if (( unborn )); then ++ ref=$(__git_prompt_git symbolic-ref --short HEAD 2> /dev/null) || return 0 ++ elif [[ "$ref" == HEAD ]]; then ++ ref=$(__git_prompt_git describe --tags --exact-match HEAD 2> /dev/null) \ ++ || ref=$(__git_prompt_git rev-parse --short HEAD 2> /dev/null) \ ++ || return 0 ++ fi + + # Use global ZSH_THEME_GIT_SHOW_UPSTREAM=1 for including upstream remote info + local upstream +@@ -244,7 +254,8 @@ function parse_git_dirty() { + FLAGS+="--ignore-submodules=${GIT_STATUS_IGNORE_SUBMODULES:-dirty}" + ;; + esac +- STATUS=$(__git_prompt_git status ${FLAGS} 2> /dev/null | tail -n 1) ++ # only non-emptiness matters, so keep one line instead of the whole list ++ __git_prompt_git status ${FLAGS} 2> /dev/null | read -r STATUS + fi + if [[ -n $STATUS ]]; then + echo "$ZSH_THEME_GIT_PROMPT_DIRTY" diff --git a/tasks/ohmyzsh__ohmyzsh-14069/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14069/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d3066340b1c376424520d4eb788de7b3332052a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14069/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 426650fbe8943879af72703556ae5d1eb2eac734 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14069/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14069/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14069/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14073/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14073/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7f85d14cf0ec2432431ce51881570fbac46b8bf6 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14073/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 426650fbe8943879af72703556ae5d1eb2eac734 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 426650fbe8943879af72703556ae5d1eb2eac734 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 426650fbe8943879af72703556ae5d1eb2eac734 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14073/instruction.md b/tasks/ohmyzsh__ohmyzsh-14073/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e297cdc6796819a30ed060c6d2fe44e4a6774af8 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14073/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** perf(spectrum): build the FG and BG tables without a 256-iteration loop + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Fill the `$FG` and `$BG` colour tables with a brace expansion zipped against the code list instead of looping over the 256 codes with two subscript assignments each. +- The escape character is written as `$'\e'` instead of a literal control byte in the source. +- The resulting arrays are byte-identical (all 256 keys of each, plus `$FX`, compared against the current file), and `spectrum_ls` / `spectrum_bls` output is unchanged. + +## Other comments: + +Part of a series of small startup-time PRs, and the smallest of them. Measured on macOS arm64, zsh 5.9: 0.85 ms to 0.35 ms per interactive start. + +🤖 Co-authored with Claude Code + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `426650fbe894`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14073/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14073/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..5fe14f61bfe6ea8c2d72841e6f94d921b6ff64ba --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14073/solution/patch.diff @@ -0,0 +1,25 @@ +diff --git a/lib/spectrum.zsh b/lib/spectrum.zsh +index 31e37792..86a939e8 100644 +--- a/lib/spectrum.zsh ++++ b/lib/spectrum.zsh +@@ -14,10 +14,16 @@ FX=( + reverse "%{%}" no-reverse "%{%}" + ) + +-for color in {000..255}; do +- FG[$color]="%{[38;5;${color}m%}" +- BG[$color]="%{[48;5;${color}m%}" +-done ++# Build the tables with array operations instead of a 256-iteration loop ++() { ++ setopt localoptions noksharrays ++ local -a codes fg bg ++ codes=({000..255}) ++ fg=( "%{"$'\e'"[38;5;"${^codes}"m%}" ) ++ bg=( "%{"$'\e'"[48;5;"${^codes}"m%}" ) ++ FG=( ${codes:^fg} ) ++ BG=( ${codes:^bg} ) ++} + + # Show all 256 colors with color number + function spectrum_ls() { diff --git a/tasks/ohmyzsh__ohmyzsh-14073/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14073/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14073/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14073/task.toml b/tasks/ohmyzsh__ohmyzsh-14073/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..891268f3ed77f1efdf370e7bd159e1c9b30eb4ed --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14073/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14073" +description = "perf(spectrum): build the FG and BG tables without a 256-iteration loop" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "426650fbe8943879af72703556ae5d1eb2eac734" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14073" +source_access = "auto" +built_at = "2026-11-16T16:09:56.980532+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:00f13aa32fd0c487fd04554bd7141bfef69217178672923a7386cfbc3789211b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-09T15:03:49Z" +diff_format = "unified" +context_files = [ + "lib/spectrum.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 14 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.984334+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3f5f1ee28d2ad917c2a988746b3228307fc5d51980b9e3d4004db674cd2dce87" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14073/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14073/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14073/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14073/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14073/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e297cdc6796819a30ed060c6d2fe44e4a6774af8 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14073/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** perf(spectrum): build the FG and BG tables without a 256-iteration loop + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Fill the `$FG` and `$BG` colour tables with a brace expansion zipped against the code list instead of looping over the 256 codes with two subscript assignments each. +- The escape character is written as `$'\e'` instead of a literal control byte in the source. +- The resulting arrays are byte-identical (all 256 keys of each, plus `$FX`, compared against the current file), and `spectrum_ls` / `spectrum_bls` output is unchanged. + +## Other comments: + +Part of a series of small startup-time PRs, and the smallest of them. Measured on macOS arm64, zsh 5.9: 0.85 ms to 0.35 ms per interactive start. + +🤖 Co-authored with Claude Code + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `426650fbe894`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14073/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14073/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..5fe14f61bfe6ea8c2d72841e6f94d921b6ff64ba --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14073/tests/oracle.patch @@ -0,0 +1,25 @@ +diff --git a/lib/spectrum.zsh b/lib/spectrum.zsh +index 31e37792..86a939e8 100644 +--- a/lib/spectrum.zsh ++++ b/lib/spectrum.zsh +@@ -14,10 +14,16 @@ FX=( + reverse "%{%}" no-reverse "%{%}" + ) + +-for color in {000..255}; do +- FG[$color]="%{[38;5;${color}m%}" +- BG[$color]="%{[48;5;${color}m%}" +-done ++# Build the tables with array operations instead of a 256-iteration loop ++() { ++ setopt localoptions noksharrays ++ local -a codes fg bg ++ codes=({000..255}) ++ fg=( "%{"$'\e'"[38;5;"${^codes}"m%}" ) ++ bg=( "%{"$'\e'"[48;5;"${^codes}"m%}" ) ++ FG=( ${codes:^fg} ) ++ BG=( ${codes:^bg} ) ++} + + # Show all 256 colors with color number + function spectrum_ls() { diff --git a/tasks/ohmyzsh__ohmyzsh-14073/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14073/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d3066340b1c376424520d4eb788de7b3332052a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14073/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 426650fbe8943879af72703556ae5d1eb2eac734 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14073/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14073/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14073/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14074/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14074/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7f85d14cf0ec2432431ce51881570fbac46b8bf6 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14074/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 426650fbe8943879af72703556ae5d1eb2eac734 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 426650fbe8943879af72703556ae5d1eb2eac734 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 426650fbe8943879af72703556ae5d1eb2eac734 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14074/instruction.md b/tasks/ohmyzsh__ohmyzsh-14074/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b144346af8745c94b8920572780e73ce52477cb5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14074/instruction.md @@ -0,0 +1,86 @@ +# Issue + +**Title:** chore(core): refresh links in install and upgrade + +## Description + +## Summary + +The post-install and post-upgrade messages drifted apart and both had some awkward wording ("Join our Discord: Discord server"). This makes them say the same thing, styled to match their surroundings: bullets in `install.sh`, bold blue lines in `upgrade.sh`. + +- Drops the redundant "Discord: Discord server" wording +- Adds the Bluesky account (`@ohmyz.sh`) +- Reframes the shop line as "help support the project" and adds an Open Collective sponsor link +- Mentions stickers, shirts, and swag instead of listing products +- Keeps the block to four short lines so it is easy to skim + +No changes to the ASCII logo, `fmt_link`, `supports_hyperlinks`, or anything else in either file. + +## Before / after + +### `tools/install.sh` (after "Before you scream Oh My Zsh!...") + +Before (hyperlinks off): +``` +• Follow us on X: https://x.com/ohmyzsh +• Join our Discord community: https://discord.gg/ohmyzsh +• Get stickers, t-shirts, coffee mugs and more: https://commitgoods.com/collections/oh-my-zsh +``` + +After (hyperlinks off): +``` +• Follow along on X (https://x.com/ohmyzsh) or Bluesky (https://bsky.app/profile/ohmyz.sh) +• Questions or ideas? Join the community on https://discord.gg/ohmyzsh +• Help support the project: sponsor us on https://opencollective.com/ohmyzsh, + or grab stickers, shirts, and swag from https://commitgoods.com/ohmyzsh +``` + +After (hyperlinks on, link text shown; each name is a clickable OSC 8 link): +``` +• Follow along on X (@ohmyzsh) or Bluesky (@ohmyz.sh) +• Questions or ideas? Join the community on Discord +• Help support the project: sponsor us on Open Collective, + or grab stickers, shirts, and swag from CommitGoods +``` + +### `tools/upgrade.sh` (after the update message, bold blue) + +Before (hyperlinks off): +``` +To keep up with the latest news and updates, follow us on X: https://x.com/ohmyzsh +Want to get involved in the community? Join our Discord: https://discord.gg/ohmyzsh +Get your Oh My Zsh swag at: https://commitgoods.com/collections/oh-my-zsh +``` + +After (hyperlinks off): +``` +Follow along on X (https://x.com/ohmyzsh) or Bluesky (https://bsky.app/profile/ohmyz.sh) +Questions or ideas? Join the community on https://discord.gg/ohmyzsh +Help support the project: sponsor us on https://opencollective.com/ohmyzsh, +or grab stickers, shirts, and swag from https://commitgoods.com/ohmyzsh +``` + +After (hyperlinks on, link text shown): +``` +Follow along on X (@ohmyzsh) or Bluesky (@ohmyz.sh) +Questions or ideas? Join the community on Discord +Help support the project: sponsor us on Open Collective, +or grab stickers, shirts, and swag from CommitGoods +``` + +## Fallback behavior + +`fmt_link` prints the raw URL (underlined on a tty) when `supports_hyperlinks` is false, so the link text in each line was chosen to read well either way. In the fallback the parenthesized handles become parenthesized URLs, and "sponsor us on Open Collective" becomes "sponsor us on https://opencollective.com/ohmyzsh". Both files were rendered with `FORCE_HYPERLINK=1` and `FORCE_HYPERLINK=0` to confirm the output above. + +## Checks + +- `https://commitgoods.com/ohmyzsh` returns a 301 to `/collections/oh-my-zsh`, which returns 200, so the short URL is used in both files. +- `ohmyz.sh` resolves as a Bluesky handle via the public API and the profile page loads. +- `https://opencollective.com/ohmyzsh` returns 200. +- shellcheck output on both files is unchanged from `master` (only pre-existing findings; it cannot parse the zsh `case` glob in `upgrade.sh`, as before). + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `426650fbe894`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14074/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14074/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..bebb61da1dab52cb204a8766c9dbf39b61caa0d6 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14074/solution/patch.diff @@ -0,0 +1,44 @@ +diff --git a/tools/install.sh b/tools/install.sh +index 83ff0cab..4a02eff5 100755 +--- a/tools/install.sh ++++ b/tools/install.sh +@@ -528,9 +528,10 @@ print_success() { + "$(fmt_code "$(fmt_link ".zshrc" "file://$zdot/.zshrc" --text)")" \ + "file to select plugins, themes, and options." + printf '\n' +- printf '%s\n' "• Follow us on X: $(fmt_link @ohmyzsh https://x.com/ohmyzsh)" +- printf '%s\n' "• Join our Discord community: $(fmt_link "Discord server" https://discord.gg/ohmyzsh)" +- printf '%s\n' "• Get stickers, t-shirts, coffee mugs and more: $(fmt_link "CommitGoods Shop" https://commitgoods.com/collections/oh-my-zsh)" ++ printf '%s\n' "• Follow along on X ($(fmt_link @ohmyzsh https://x.com/ohmyzsh)) or Bluesky ($(fmt_link @ohmyz.sh https://bsky.app/profile/ohmyz.sh))" ++ printf '%s\n' "• Questions or ideas? Join the community on $(fmt_link Discord https://discord.gg/ohmyzsh)" ++ printf '%s\n' "• Help support the project: sponsor us on $(fmt_link "Open Collective" https://opencollective.com/ohmyzsh)," ++ printf '%s\n' " or grab stickers, shirts, and swag from $(fmt_link CommitGoods https://commitgoods.com/ohmyzsh)" + printf '%s\n' $FMT_RESET + } + +diff --git a/tools/upgrade.sh b/tools/upgrade.sh +index df8d0f34..8a875e27 100755 +--- a/tools/upgrade.sh ++++ b/tools/upgrade.sh +@@ -271,9 +271,18 @@ if LANG= git pull --quiet --rebase $remote $branch; then + printf '%s %s %s %s /____/ %s %s %s %s\n' $RAINBOW $RESET + printf '\n' + printf "${BLUE}%s${RESET}\n\n" "$message" +- printf "${BLUE}${BOLD}%s %s${RESET}\n" "To keep up with the latest news and updates, follow us on X:" "$(fmt_link @ohmyzsh https://x.com/ohmyzsh)" +- printf "${BLUE}${BOLD}%s %s${RESET}\n" "Want to get involved in the community? Join our Discord:" "$(fmt_link "Discord server" https://discord.gg/ohmyzsh)" +- printf "${BLUE}${BOLD}%s %s${RESET}\n" "Get your Oh My Zsh swag at:" "$(fmt_link "CommitGoods Shop" https://commitgoods.com/collections/oh-my-zsh)" ++ printf "${BLUE}${BOLD}%s %s %s %s${RESET}\n" \ ++ "Follow along on X" "($(fmt_link @ohmyzsh https://x.com/ohmyzsh))" \ ++ "or Bluesky" "($(fmt_link @ohmyz.sh https://bsky.app/profile/ohmyz.sh))" ++ printf "${BLUE}${BOLD}%s %s${RESET}\n" \ ++ "Questions or ideas? Join the community on" \ ++ "$(fmt_link Discord https://discord.gg/ohmyzsh)" ++ printf "${BLUE}${BOLD}%s %s,${RESET}\n" \ ++ "Help support the project: sponsor us on" \ ++ "$(fmt_link "Open Collective" https://opencollective.com/ohmyzsh)" ++ printf "${BLUE}${BOLD}%s %s${RESET}\n" \ ++ "or grab stickers, shirts, and swag from" \ ++ "$(fmt_link CommitGoods https://commitgoods.com/ohmyzsh)" + elif [[ $verbose_mode == minimal ]]; then + printf "${BLUE}%s${RESET}\n" "$message" + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14074/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14074/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14074/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14074/task.toml b/tasks/ohmyzsh__ohmyzsh-14074/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0a590678340ea28e0702da65747c3ceac6af66ad --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14074/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14074" +description = "chore(core): refresh links in install and upgrade" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "426650fbe8943879af72703556ae5d1eb2eac734" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14074" +source_access = "auto" +built_at = "2026-11-16T16:09:56.995653+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c6b47ed9fc25e4be32330bc7a2e7214c45f6d9348a9d096c5fa5051ab626645a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-07T08:08:43Z" +diff_format = "unified" +context_files = [ + "tools/install.sh", + "tools/upgrade.sh", +] +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.984841+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3f5f1ee28d2ad917c2a988746b3228307fc5d51980b9e3d4004db674cd2dce87" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14074/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14074/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14074/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14074/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14074/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b144346af8745c94b8920572780e73ce52477cb5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14074/tests/instruction.md @@ -0,0 +1,86 @@ +# Issue + +**Title:** chore(core): refresh links in install and upgrade + +## Description + +## Summary + +The post-install and post-upgrade messages drifted apart and both had some awkward wording ("Join our Discord: Discord server"). This makes them say the same thing, styled to match their surroundings: bullets in `install.sh`, bold blue lines in `upgrade.sh`. + +- Drops the redundant "Discord: Discord server" wording +- Adds the Bluesky account (`@ohmyz.sh`) +- Reframes the shop line as "help support the project" and adds an Open Collective sponsor link +- Mentions stickers, shirts, and swag instead of listing products +- Keeps the block to four short lines so it is easy to skim + +No changes to the ASCII logo, `fmt_link`, `supports_hyperlinks`, or anything else in either file. + +## Before / after + +### `tools/install.sh` (after "Before you scream Oh My Zsh!...") + +Before (hyperlinks off): +``` +• Follow us on X: https://x.com/ohmyzsh +• Join our Discord community: https://discord.gg/ohmyzsh +• Get stickers, t-shirts, coffee mugs and more: https://commitgoods.com/collections/oh-my-zsh +``` + +After (hyperlinks off): +``` +• Follow along on X (https://x.com/ohmyzsh) or Bluesky (https://bsky.app/profile/ohmyz.sh) +• Questions or ideas? Join the community on https://discord.gg/ohmyzsh +• Help support the project: sponsor us on https://opencollective.com/ohmyzsh, + or grab stickers, shirts, and swag from https://commitgoods.com/ohmyzsh +``` + +After (hyperlinks on, link text shown; each name is a clickable OSC 8 link): +``` +• Follow along on X (@ohmyzsh) or Bluesky (@ohmyz.sh) +• Questions or ideas? Join the community on Discord +• Help support the project: sponsor us on Open Collective, + or grab stickers, shirts, and swag from CommitGoods +``` + +### `tools/upgrade.sh` (after the update message, bold blue) + +Before (hyperlinks off): +``` +To keep up with the latest news and updates, follow us on X: https://x.com/ohmyzsh +Want to get involved in the community? Join our Discord: https://discord.gg/ohmyzsh +Get your Oh My Zsh swag at: https://commitgoods.com/collections/oh-my-zsh +``` + +After (hyperlinks off): +``` +Follow along on X (https://x.com/ohmyzsh) or Bluesky (https://bsky.app/profile/ohmyz.sh) +Questions or ideas? Join the community on https://discord.gg/ohmyzsh +Help support the project: sponsor us on https://opencollective.com/ohmyzsh, +or grab stickers, shirts, and swag from https://commitgoods.com/ohmyzsh +``` + +After (hyperlinks on, link text shown): +``` +Follow along on X (@ohmyzsh) or Bluesky (@ohmyz.sh) +Questions or ideas? Join the community on Discord +Help support the project: sponsor us on Open Collective, +or grab stickers, shirts, and swag from CommitGoods +``` + +## Fallback behavior + +`fmt_link` prints the raw URL (underlined on a tty) when `supports_hyperlinks` is false, so the link text in each line was chosen to read well either way. In the fallback the parenthesized handles become parenthesized URLs, and "sponsor us on Open Collective" becomes "sponsor us on https://opencollective.com/ohmyzsh". Both files were rendered with `FORCE_HYPERLINK=1` and `FORCE_HYPERLINK=0` to confirm the output above. + +## Checks + +- `https://commitgoods.com/ohmyzsh` returns a 301 to `/collections/oh-my-zsh`, which returns 200, so the short URL is used in both files. +- `ohmyz.sh` resolves as a Bluesky handle via the public API and the profile page loads. +- `https://opencollective.com/ohmyzsh` returns 200. +- shellcheck output on both files is unchanged from `master` (only pre-existing findings; it cannot parse the zsh `case` glob in `upgrade.sh`, as before). + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `426650fbe894`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14074/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14074/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..bebb61da1dab52cb204a8766c9dbf39b61caa0d6 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14074/tests/oracle.patch @@ -0,0 +1,44 @@ +diff --git a/tools/install.sh b/tools/install.sh +index 83ff0cab..4a02eff5 100755 +--- a/tools/install.sh ++++ b/tools/install.sh +@@ -528,9 +528,10 @@ print_success() { + "$(fmt_code "$(fmt_link ".zshrc" "file://$zdot/.zshrc" --text)")" \ + "file to select plugins, themes, and options." + printf '\n' +- printf '%s\n' "• Follow us on X: $(fmt_link @ohmyzsh https://x.com/ohmyzsh)" +- printf '%s\n' "• Join our Discord community: $(fmt_link "Discord server" https://discord.gg/ohmyzsh)" +- printf '%s\n' "• Get stickers, t-shirts, coffee mugs and more: $(fmt_link "CommitGoods Shop" https://commitgoods.com/collections/oh-my-zsh)" ++ printf '%s\n' "• Follow along on X ($(fmt_link @ohmyzsh https://x.com/ohmyzsh)) or Bluesky ($(fmt_link @ohmyz.sh https://bsky.app/profile/ohmyz.sh))" ++ printf '%s\n' "• Questions or ideas? Join the community on $(fmt_link Discord https://discord.gg/ohmyzsh)" ++ printf '%s\n' "• Help support the project: sponsor us on $(fmt_link "Open Collective" https://opencollective.com/ohmyzsh)," ++ printf '%s\n' " or grab stickers, shirts, and swag from $(fmt_link CommitGoods https://commitgoods.com/ohmyzsh)" + printf '%s\n' $FMT_RESET + } + +diff --git a/tools/upgrade.sh b/tools/upgrade.sh +index df8d0f34..8a875e27 100755 +--- a/tools/upgrade.sh ++++ b/tools/upgrade.sh +@@ -271,9 +271,18 @@ if LANG= git pull --quiet --rebase $remote $branch; then + printf '%s %s %s %s /____/ %s %s %s %s\n' $RAINBOW $RESET + printf '\n' + printf "${BLUE}%s${RESET}\n\n" "$message" +- printf "${BLUE}${BOLD}%s %s${RESET}\n" "To keep up with the latest news and updates, follow us on X:" "$(fmt_link @ohmyzsh https://x.com/ohmyzsh)" +- printf "${BLUE}${BOLD}%s %s${RESET}\n" "Want to get involved in the community? Join our Discord:" "$(fmt_link "Discord server" https://discord.gg/ohmyzsh)" +- printf "${BLUE}${BOLD}%s %s${RESET}\n" "Get your Oh My Zsh swag at:" "$(fmt_link "CommitGoods Shop" https://commitgoods.com/collections/oh-my-zsh)" ++ printf "${BLUE}${BOLD}%s %s %s %s${RESET}\n" \ ++ "Follow along on X" "($(fmt_link @ohmyzsh https://x.com/ohmyzsh))" \ ++ "or Bluesky" "($(fmt_link @ohmyz.sh https://bsky.app/profile/ohmyz.sh))" ++ printf "${BLUE}${BOLD}%s %s${RESET}\n" \ ++ "Questions or ideas? Join the community on" \ ++ "$(fmt_link Discord https://discord.gg/ohmyzsh)" ++ printf "${BLUE}${BOLD}%s %s,${RESET}\n" \ ++ "Help support the project: sponsor us on" \ ++ "$(fmt_link "Open Collective" https://opencollective.com/ohmyzsh)" ++ printf "${BLUE}${BOLD}%s %s${RESET}\n" \ ++ "or grab stickers, shirts, and swag from" \ ++ "$(fmt_link CommitGoods https://commitgoods.com/ohmyzsh)" + elif [[ $verbose_mode == minimal ]]; then + printf "${BLUE}%s${RESET}\n" "$message" + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14074/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14074/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d3066340b1c376424520d4eb788de7b3332052a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14074/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 426650fbe8943879af72703556ae5d1eb2eac734 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14074/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14074/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14074/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14079/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14079/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..67180fd457b554f30be25a1c8cc3002a760e254d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14079/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 8d10cc948887e3cff29923d758999afa6edf87fb 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 8d10cc948887e3cff29923d758999afa6edf87fb \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 8d10cc948887e3cff29923d758999afa6edf87fb \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14079/instruction.md b/tasks/ohmyzsh__ohmyzsh-14079/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..86f139590a6b175786f2acf4d4c2dd692e4cb3c3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14079/instruction.md @@ -0,0 +1,39 @@ +# Issue + +**Title:** feat(herdr): add plugin for herdr + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +Adds a plugin for [herdr](https://herdr.dev), the runtime for coding agents. It keeps agent terminals running in the background across projects and machines. + +- Completion generated from `herdr completion zsh`, cached in `$ZSH_CACHE_DIR/completions/_herdr` and refreshed in the background on load (same pattern as `gh`, `deno`, `gcx`). +- `hrdr` aliases for the daily commands: status, update, session list/attach, remote attach, agent list, workspace list/create, worktree create, pane split, server reload-config. +- `hrdrs`: interactive session picker. Uses fzf when installed, falls back to zsh's `select` menu otherwise, so there is no hard dependency. +- `herdr_prompt_info`: shows the current pane ID in the prompt when the shell is inside herdr. Reads env vars only, no forks. Wraps with `ZSH_THEME_HERDR_PROMPT_PREFIX` / `_SUFFIX`, same shape as `go_prompt_info` (#8924). +- README written as a short walkthrough of the common workflows so the plugin doubles as a way to learn the CLI. + +## Other comments: + +Alias use case: herdr users run `status`, `session attach`, `agent list` and `workspace create` many times a day, and herdr's own subcommand tree is deep (`herdr server reload-config`). The `hrdr` prefix was chosen because `hd` and `hr` are already taken by the hanami plugin. + +Tested against herdr 0.8.0 on macOS. All commands and flags in the README were checked against the binary's generated completion script. The session picker was tested on both the fzf and the fallback path, including cancel, EOF and empty session list. + +Drafted with Claude Code; reviewed and tested by me. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8d10cc948887`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14079/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14079/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6e49de45a98afe732cf18dd02f6187760b6c3bbd --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14079/solution/patch.diff @@ -0,0 +1,243 @@ +diff --git a/plugins/herdr/README.md b/plugins/herdr/README.md +new file mode 100644 +index 00000000..5a24f23c +--- /dev/null ++++ b/plugins/herdr/README.md +@@ -0,0 +1,163 @@ ++# herdr plugin ++ ++This plugin adds completion, aliases, an interactive session picker and a prompt ++function for [herdr](https://herdr.dev), the runtime your ++coding agents live on. herdr keeps agent terminals running in the background across ++projects and machines, so you can close your terminal, reconnect later, and pick up ++where the agents left off. ++ ++To use it, add `herdr` to the plugins array in your zshrc file: ++ ++```zsh ++plugins=(... herdr) ++``` ++ ++Install herdr first if you have not already: ++ ++```sh ++curl -fsSL https://herdr.dev/install.sh | sh # or: brew install herdr ++``` ++ ++## Learning herdr from the terminal ++ ++The fastest way to explore herdr is tab completion. Every command group and flag shows a ++short description, so you can discover what is available without leaving the shell: ++ ++``` ++$ herdr ++agent -- Control and inspect agent panes ++session -- Manage named persistent sessions ++workspace -- Manage workspaces over the socket API ++worktree -- Manage Git worktree-backed workspaces ++... ++$ herdr agent ++list -- List agents ++prompt -- Submit a prompt to an agent ++start -- Start a supported interactive agent in an existing pane ++wait -- Wait until an agent reaches one of the requested states ++... ++``` ++ ++A few other ways to learn as you go: ++ ++- `herdr ` with no subcommand prints that group's help, for example `herdr pane`. ++- `herdr --skill` prints the instructions herdr gives to agents that drive it. It is a ++ good tour of the full command surface. ++- Most control commands return JSON, so you can pipe them into `jq` in scripts. ++ ++## Common workflows ++ ++### Start and reconnect ++ ++```sh ++herdr # launch, or attach to the default session ++herdr --session work # use or create a named session ++herdr session list # see running and stopped sessions ++herdr session attach work # reconnect to a named session ++herdr status # check the local client and running server ++herdr update # install the latest release ++``` ++ ++### Organize work into workspaces and tabs ++ ++```sh ++herdr workspace list ++herdr workspace create --cwd ~/projects/app ++herdr tab create ++herdr pane split --direction right ++herdr worktree create --branch feature/login # open a Git worktree in its own workspace ++``` ++ ++### Run and watch agents ++ ++```sh ++herdr agent list # what is running, and is it idle, working or blocked ++herdr agent start reviewer --kind claude --pane w1:p2 ++herdr agent prompt reviewer "review the last commit" --wait ++herdr agent read reviewer # read the agent's terminal output ++herdr agent wait reviewer --until idle ++herdr agent attach reviewer # jump straight into that terminal ++``` ++ ++### Work across machines ++ ++```sh ++herdr --remote user@build-box # attach through SSH with your local keybindings ++``` ++ ++### Keep the server healthy ++ ++```sh ++herdr config check # validate config.toml ++herdr server reload-config # apply config changes without restarting panes ++herdr server stop ++herdr channel set preview # switch between stable and preview releases ++herdr integration status # which agent CLIs have herdr hooks installed ++``` ++ ++See the [CLI reference](https://herdr.dev/docs/cli-reference/) for every command and flag. ++ ++## Aliases ++ ++| Alias | Command | ++| ------- | ----------------------------- | ++| `hrdr` | `herdr` | ++| `hrdrst` | `herdr status` | ++| `hrdrup` | `herdr update` | ++| `hrdrsl` | `herdr session list` | ++| `hrdrsa` | `herdr session attach` | ++| `hrdrr` | `herdr --remote` | ++| `hrdral` | `herdr agent list` | ++| `hrdrwl` | `herdr workspace list` | ++| `hrdrwc` | `herdr workspace create` | ++| `hrdrwt` | `herdr worktree create` | ++| `hrdrps` | `herdr pane split` | ++| `hrdrrc` | `herdr server reload-config` | ++ ++Tab completion works through the aliases too, so `hrdr agent ` completes the same ++way `herdr agent ` does. ++ ++## Session picker ++ ++`hrdrs` lists your herdr sessions and attaches to the one you pick. It uses ++[fzf](https://github.com/junegunn/fzf) when it is installed and falls back to a numbered ++menu otherwise, so it works everywhere. ++ ++``` ++$ hrdrs ++name status directory ++1) default running /Users/me/.config/herdr ++2) work stopped /Users/me/projects/app ++Attach to session: 2 ++``` ++ ++## Prompt ++ ++This plugin provides the `herdr_prompt_info` function to show the current pane ID in ++your prompt when the shell is running inside herdr. It reads environment variables only, ++so it adds no cost to prompt rendering. ++ ++For example: ++``` ++PROMPT="%~$ " ++RPROMPT='$(herdr_prompt_info)' ++``` ++changes your prompt inside a herdr pane to: ++``` ++~/projects/app$ ▋ w1:p4 ++``` ++and shows nothing outside herdr. ++ ++Wrap it with `ZSH_THEME_HERDR_PROMPT_PREFIX` and `ZSH_THEME_HERDR_PROMPT_SUFFIX`, for ++example: ++``` ++ZSH_THEME_HERDR_PROMPT_PREFIX="%{$fg[cyan]%}[herdr " ++ZSH_THEME_HERDR_PROMPT_SUFFIX="]%{$reset_color%}" ++``` ++ ++## Cache ++ ++This plugin caches the completion script and automatically updates it when the plugin is ++loaded, which is usually when you start a new terminal emulator. ++ ++The cache is stored at `$ZSH_CACHE_DIR/completions/_herdr`. +diff --git a/plugins/herdr/herdr.plugin.zsh b/plugins/herdr/herdr.plugin.zsh +new file mode 100644 +index 00000000..e5d12eed +--- /dev/null ++++ b/plugins/herdr/herdr.plugin.zsh +@@ -0,0 +1,68 @@ ++# Aliases, helpers and completion for herdr (https://herdr.dev), the runtime for coding agents. ++ ++# PROMPT ++# Defined before the herdr check so themes can reference it on machines without herdr. ++function herdr_prompt_info { ++ [[ "$HERDR_ENV" == 1 ]] || return ++ echo "${ZSH_THEME_HERDR_PROMPT_PREFIX}${HERDR_PANE_ID:gs/%/%%}${ZSH_THEME_HERDR_PROMPT_SUFFIX}" ++} ++ ++if (( ! $+commands[herdr] )); then ++ return ++fi ++ ++# ALIASES ++alias hrdr='herdr' ++alias hrdrst='herdr status' ++alias hrdrup='herdr update' ++alias hrdrsl='herdr session list' ++alias hrdrsa='herdr session attach' ++alias hrdrr='herdr --remote' ++alias hrdral='herdr agent list' ++alias hrdrwl='herdr workspace list' ++alias hrdrwc='herdr workspace create' ++alias hrdrwt='herdr worktree create' ++alias hrdrps='herdr pane split' ++alias hrdrrc='herdr server reload-config' ++ ++# FUNCTIONS ++# Pick a session and attach to it, with fzf if available or a numbered menu otherwise. ++function hrdrs { ++ setopt localoptions extendedglob ++ local -a lines ++ lines=("${(@f)$(herdr session list 2>/dev/null)}") ++ lines=("${(@)lines%%[[:space:]]#[^[:space:]]#}") # drop the socket column ++ if (( $#lines < 2 )); then ++ print "hrdrs: no herdr sessions found" >&2 ++ return 1 ++ fi ++ ++ local choice ++ if (( $+commands[fzf] )); then ++ choice=$(print -l -- "${lines[@]}" | fzf --header-lines=1 --prompt='herdr session> ') || return ++ else ++ print -- "${lines[1]}" ++ local PS3="Attach to session: " ++ select choice in "${lines[@]:1}"; do ++ [[ -n "$choice" ]] && break ++ done ++ fi ++ [[ -n "$choice" ]] || return 1 ++ ++ herdr session attach "${${(z)choice}[1]}" ++} ++ ++# COMPLETION ++# If the completion file doesn't exist yet, we need to autoload it and ++# bind it to `herdr`. Otherwise, compinit will have already done that. ++if [[ ! -f "$ZSH_CACHE_DIR/completions/_herdr" ]]; then ++ typeset -g -A _comps ++ autoload -Uz _herdr ++ _comps[herdr]=_herdr ++fi ++ ++zmodload -F zsh/files b:zf_mv ++() { ++ local TMPPREFIX="$ZSH_CACHE_DIR/completions/_herdr" ++ zf_mv -f -- =( herdr completion zsh < /dev/null 2> /dev/null ) "$TMPPREFIX" ++} &| diff --git a/tasks/ohmyzsh__ohmyzsh-14079/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14079/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14079/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14079/task.toml b/tasks/ohmyzsh__ohmyzsh-14079/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..eb38d8090e5a76bf738db64a5ad52e20774bf0af --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14079/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14079" +description = "feat(herdr): add plugin for herdr" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "8d10cc948887e3cff29923d758999afa6edf87fb" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14079" +source_access = "auto" +built_at = "2026-11-16T16:09:56.977179+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:eea87b2414e3c59cf94fe337994193c2138c7725a123ef627f08a1ac7e45768e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-10T11:16:55Z" +diff_format = "unified" +context_files = [ + "plugins/herdr/README.md", + "plugins/herdr/herdr.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 231 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.985342+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:24c0e7a0d3810ffe038050afcc82ce8f3d512f8bcdd324ae675201a605de46c7" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14079/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14079/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14079/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14079/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14079/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..86f139590a6b175786f2acf4d4c2dd692e4cb3c3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14079/tests/instruction.md @@ -0,0 +1,39 @@ +# Issue + +**Title:** feat(herdr): add plugin for herdr + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +Adds a plugin for [herdr](https://herdr.dev), the runtime for coding agents. It keeps agent terminals running in the background across projects and machines. + +- Completion generated from `herdr completion zsh`, cached in `$ZSH_CACHE_DIR/completions/_herdr` and refreshed in the background on load (same pattern as `gh`, `deno`, `gcx`). +- `hrdr` aliases for the daily commands: status, update, session list/attach, remote attach, agent list, workspace list/create, worktree create, pane split, server reload-config. +- `hrdrs`: interactive session picker. Uses fzf when installed, falls back to zsh's `select` menu otherwise, so there is no hard dependency. +- `herdr_prompt_info`: shows the current pane ID in the prompt when the shell is inside herdr. Reads env vars only, no forks. Wraps with `ZSH_THEME_HERDR_PROMPT_PREFIX` / `_SUFFIX`, same shape as `go_prompt_info` (#8924). +- README written as a short walkthrough of the common workflows so the plugin doubles as a way to learn the CLI. + +## Other comments: + +Alias use case: herdr users run `status`, `session attach`, `agent list` and `workspace create` many times a day, and herdr's own subcommand tree is deep (`herdr server reload-config`). The `hrdr` prefix was chosen because `hd` and `hr` are already taken by the hanami plugin. + +Tested against herdr 0.8.0 on macOS. All commands and flags in the README were checked against the binary's generated completion script. The session picker was tested on both the fzf and the fallback path, including cancel, EOF and empty session list. + +Drafted with Claude Code; reviewed and tested by me. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `8d10cc948887`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14079/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14079/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6e49de45a98afe732cf18dd02f6187760b6c3bbd --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14079/tests/oracle.patch @@ -0,0 +1,243 @@ +diff --git a/plugins/herdr/README.md b/plugins/herdr/README.md +new file mode 100644 +index 00000000..5a24f23c +--- /dev/null ++++ b/plugins/herdr/README.md +@@ -0,0 +1,163 @@ ++# herdr plugin ++ ++This plugin adds completion, aliases, an interactive session picker and a prompt ++function for [herdr](https://herdr.dev), the runtime your ++coding agents live on. herdr keeps agent terminals running in the background across ++projects and machines, so you can close your terminal, reconnect later, and pick up ++where the agents left off. ++ ++To use it, add `herdr` to the plugins array in your zshrc file: ++ ++```zsh ++plugins=(... herdr) ++``` ++ ++Install herdr first if you have not already: ++ ++```sh ++curl -fsSL https://herdr.dev/install.sh | sh # or: brew install herdr ++``` ++ ++## Learning herdr from the terminal ++ ++The fastest way to explore herdr is tab completion. Every command group and flag shows a ++short description, so you can discover what is available without leaving the shell: ++ ++``` ++$ herdr ++agent -- Control and inspect agent panes ++session -- Manage named persistent sessions ++workspace -- Manage workspaces over the socket API ++worktree -- Manage Git worktree-backed workspaces ++... ++$ herdr agent ++list -- List agents ++prompt -- Submit a prompt to an agent ++start -- Start a supported interactive agent in an existing pane ++wait -- Wait until an agent reaches one of the requested states ++... ++``` ++ ++A few other ways to learn as you go: ++ ++- `herdr ` with no subcommand prints that group's help, for example `herdr pane`. ++- `herdr --skill` prints the instructions herdr gives to agents that drive it. It is a ++ good tour of the full command surface. ++- Most control commands return JSON, so you can pipe them into `jq` in scripts. ++ ++## Common workflows ++ ++### Start and reconnect ++ ++```sh ++herdr # launch, or attach to the default session ++herdr --session work # use or create a named session ++herdr session list # see running and stopped sessions ++herdr session attach work # reconnect to a named session ++herdr status # check the local client and running server ++herdr update # install the latest release ++``` ++ ++### Organize work into workspaces and tabs ++ ++```sh ++herdr workspace list ++herdr workspace create --cwd ~/projects/app ++herdr tab create ++herdr pane split --direction right ++herdr worktree create --branch feature/login # open a Git worktree in its own workspace ++``` ++ ++### Run and watch agents ++ ++```sh ++herdr agent list # what is running, and is it idle, working or blocked ++herdr agent start reviewer --kind claude --pane w1:p2 ++herdr agent prompt reviewer "review the last commit" --wait ++herdr agent read reviewer # read the agent's terminal output ++herdr agent wait reviewer --until idle ++herdr agent attach reviewer # jump straight into that terminal ++``` ++ ++### Work across machines ++ ++```sh ++herdr --remote user@build-box # attach through SSH with your local keybindings ++``` ++ ++### Keep the server healthy ++ ++```sh ++herdr config check # validate config.toml ++herdr server reload-config # apply config changes without restarting panes ++herdr server stop ++herdr channel set preview # switch between stable and preview releases ++herdr integration status # which agent CLIs have herdr hooks installed ++``` ++ ++See the [CLI reference](https://herdr.dev/docs/cli-reference/) for every command and flag. ++ ++## Aliases ++ ++| Alias | Command | ++| ------- | ----------------------------- | ++| `hrdr` | `herdr` | ++| `hrdrst` | `herdr status` | ++| `hrdrup` | `herdr update` | ++| `hrdrsl` | `herdr session list` | ++| `hrdrsa` | `herdr session attach` | ++| `hrdrr` | `herdr --remote` | ++| `hrdral` | `herdr agent list` | ++| `hrdrwl` | `herdr workspace list` | ++| `hrdrwc` | `herdr workspace create` | ++| `hrdrwt` | `herdr worktree create` | ++| `hrdrps` | `herdr pane split` | ++| `hrdrrc` | `herdr server reload-config` | ++ ++Tab completion works through the aliases too, so `hrdr agent ` completes the same ++way `herdr agent ` does. ++ ++## Session picker ++ ++`hrdrs` lists your herdr sessions and attaches to the one you pick. It uses ++[fzf](https://github.com/junegunn/fzf) when it is installed and falls back to a numbered ++menu otherwise, so it works everywhere. ++ ++``` ++$ hrdrs ++name status directory ++1) default running /Users/me/.config/herdr ++2) work stopped /Users/me/projects/app ++Attach to session: 2 ++``` ++ ++## Prompt ++ ++This plugin provides the `herdr_prompt_info` function to show the current pane ID in ++your prompt when the shell is running inside herdr. It reads environment variables only, ++so it adds no cost to prompt rendering. ++ ++For example: ++``` ++PROMPT="%~$ " ++RPROMPT='$(herdr_prompt_info)' ++``` ++changes your prompt inside a herdr pane to: ++``` ++~/projects/app$ ▋ w1:p4 ++``` ++and shows nothing outside herdr. ++ ++Wrap it with `ZSH_THEME_HERDR_PROMPT_PREFIX` and `ZSH_THEME_HERDR_PROMPT_SUFFIX`, for ++example: ++``` ++ZSH_THEME_HERDR_PROMPT_PREFIX="%{$fg[cyan]%}[herdr " ++ZSH_THEME_HERDR_PROMPT_SUFFIX="]%{$reset_color%}" ++``` ++ ++## Cache ++ ++This plugin caches the completion script and automatically updates it when the plugin is ++loaded, which is usually when you start a new terminal emulator. ++ ++The cache is stored at `$ZSH_CACHE_DIR/completions/_herdr`. +diff --git a/plugins/herdr/herdr.plugin.zsh b/plugins/herdr/herdr.plugin.zsh +new file mode 100644 +index 00000000..e5d12eed +--- /dev/null ++++ b/plugins/herdr/herdr.plugin.zsh +@@ -0,0 +1,68 @@ ++# Aliases, helpers and completion for herdr (https://herdr.dev), the runtime for coding agents. ++ ++# PROMPT ++# Defined before the herdr check so themes can reference it on machines without herdr. ++function herdr_prompt_info { ++ [[ "$HERDR_ENV" == 1 ]] || return ++ echo "${ZSH_THEME_HERDR_PROMPT_PREFIX}${HERDR_PANE_ID:gs/%/%%}${ZSH_THEME_HERDR_PROMPT_SUFFIX}" ++} ++ ++if (( ! $+commands[herdr] )); then ++ return ++fi ++ ++# ALIASES ++alias hrdr='herdr' ++alias hrdrst='herdr status' ++alias hrdrup='herdr update' ++alias hrdrsl='herdr session list' ++alias hrdrsa='herdr session attach' ++alias hrdrr='herdr --remote' ++alias hrdral='herdr agent list' ++alias hrdrwl='herdr workspace list' ++alias hrdrwc='herdr workspace create' ++alias hrdrwt='herdr worktree create' ++alias hrdrps='herdr pane split' ++alias hrdrrc='herdr server reload-config' ++ ++# FUNCTIONS ++# Pick a session and attach to it, with fzf if available or a numbered menu otherwise. ++function hrdrs { ++ setopt localoptions extendedglob ++ local -a lines ++ lines=("${(@f)$(herdr session list 2>/dev/null)}") ++ lines=("${(@)lines%%[[:space:]]#[^[:space:]]#}") # drop the socket column ++ if (( $#lines < 2 )); then ++ print "hrdrs: no herdr sessions found" >&2 ++ return 1 ++ fi ++ ++ local choice ++ if (( $+commands[fzf] )); then ++ choice=$(print -l -- "${lines[@]}" | fzf --header-lines=1 --prompt='herdr session> ') || return ++ else ++ print -- "${lines[1]}" ++ local PS3="Attach to session: " ++ select choice in "${lines[@]:1}"; do ++ [[ -n "$choice" ]] && break ++ done ++ fi ++ [[ -n "$choice" ]] || return 1 ++ ++ herdr session attach "${${(z)choice}[1]}" ++} ++ ++# COMPLETION ++# If the completion file doesn't exist yet, we need to autoload it and ++# bind it to `herdr`. Otherwise, compinit will have already done that. ++if [[ ! -f "$ZSH_CACHE_DIR/completions/_herdr" ]]; then ++ typeset -g -A _comps ++ autoload -Uz _herdr ++ _comps[herdr]=_herdr ++fi ++ ++zmodload -F zsh/files b:zf_mv ++() { ++ local TMPPREFIX="$ZSH_CACHE_DIR/completions/_herdr" ++ zf_mv -f -- =( herdr completion zsh < /dev/null 2> /dev/null ) "$TMPPREFIX" ++} &| diff --git a/tasks/ohmyzsh__ohmyzsh-14079/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14079/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..525ab5fe87c45ec014d91edc2f2f7dddb7c69016 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14079/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 8d10cc948887e3cff29923d758999afa6edf87fb > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14079/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14079/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14079/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14082/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14082/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a8dc63e53627a6e237252f304278f4ee3da0d6e6 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14082/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d217d05374fc3c885d5fe304cea6606e2b22911a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d217d05374fc3c885d5fe304cea6606e2b22911a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d217d05374fc3c885d5fe304cea6606e2b22911a \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14082/instruction.md b/tasks/ohmyzsh__ohmyzsh-14082/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bf754cc1924231406d766a09da17f3f956f94918 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14082/instruction.md @@ -0,0 +1,67 @@ +# Issue + +**Title:** feat(opencode): add completion and opc aliases + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [ ] The PR doesn’t replicate another PR which is already open. +- [ ] I have read the contribution guide and followed all the instructions. +- [ ] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it’s from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I’ve disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +Add a small plugin for the [OpenCode CLI](https://opencode.ai) with on-demand completion and three everyday aliases: + +| Alias | Command | Workflow | +| --- | --- | --- | +| `opc` | `opencode` | Open the terminal UI in the current or specified project | +| `opcc` | `opencode --continue` | Pick up the last session, optionally adding `--fork` | +| `opcr` | `opencode run` | Send a prompt without entering the UI, optionally attaching to an existing backend | + +The autoloaded completion function adapts the CLI-generated Yargs adapter and queries the installed CLI only when completing. No OpenCode process runs at shell startup and no generated completion cache is needed. Aliases are skipped silently when the CLI is absent and support the standard OMZ alias-disable style. + +The README emphasizes learning from tab completion, with command descriptions, partial-completion examples, and practical workflows. + +## Other comments: + +### Related contributions + +This is a proposed consolidation of #13545 by @pranavavva and #13794 by @mskadu. Thank you both for the initial completion integration and alias/workflow proposals. Both contributions are also credited in the README. + +This version uses the `opc` prefix, keeps the initial alias set small, and uses a separate autoloaded completion function instead of startup-time generation. Intended to supersede those proposals once reviewed and ready; neither is automatically closed by this PR. Feedback and testing from both authors would be welcome. + +The non-duplication checkbox is intentionally unchecked because this consolidates existing open proposals. Full contribution-guide compliance and wiki-style confirmation are left for maintainer review; contributor coordination and additional community testing remain outstanding. + +### Verification + +Tested with Zsh 5.9 and OpenCode 1.18.29: + +- Zsh syntax checks and Git whitespace checks pass. +- Real interactive Tab completion works for subcommands, nested session commands, global options, and run options through `opencode`, `opc`, `opcc`, and `opcr`. +- Alias expansion includes inserted `--continue` and `run` arguments in the completion context. +- Quoted arguments are forwarded through aliases. +- Missing CLI skips aliases silently and completion falls back to the default handler. +- Full Oh My Zsh loading with aliases disabled retains completion. +- No AI prompts or backend servers were launched during testing. + +### Known upstream limitations + +OpenCode 1.18.29 does not include default/TUI flags such as `--model` and `--fork` in its top-level completion output. Direct calls to its completion endpoint show the same limitation; the README documents it. The CLI also exposes a literal `$0` candidate and double-dash forms of short options. This adapter retains the upstream candidate list rather than maintaining a separate command schema. + +Additional community testing is welcome before merging. + +### AI assistance + +AI-assisted implementation, documentation, and testing using OpenCode. Attribution to the existing community proposals is preserved above and in the README. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d217d05374fc`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14082/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14082/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2e4380c16d2ea83316273329e233f9ab0e11be3d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14082/solution/patch.diff @@ -0,0 +1,148 @@ +diff --git a/plugins/opencode/README.md b/plugins/opencode/README.md +new file mode 100644 +index 00000000..4766720c +--- /dev/null ++++ b/plugins/opencode/README.md +@@ -0,0 +1,111 @@ ++# opencode plugin ++ ++This plugin adds completion and aliases for the [OpenCode](https://opencode.ai) CLI. ++Install OpenCode using its [installation instructions](https://opencode.ai/docs/#install), ++and make sure `opencode` is available on your `$PATH`. ++ ++To enable it, add `opencode` to the plugins array in your `.zshrc`: ++ ++```zsh ++plugins=(... opencode) ++``` ++ ++## Learning OpenCode from the terminal ++ ++Use tab completion to explore commands and their descriptions without leaving the ++shell. For example, these are some of the candidates shown by the CLI: ++ ++```text ++$ opencode ++agent -- manage agents ++models -- list all available models ++run -- run opencode with a message ++session -- manage sessions ++stats -- show token usage and cost statistics ++... ++ ++$ opencode session ++delete -- delete a session ++list -- list sessions ++ ++$ opencode run -- ++--agent -- agent to use ++--continue -- continue the last session ++--file -- file(s) to attach to message ++--model -- model to use in the format of provider/model ++... ++``` ++ ++Completion works through the aliases too. Type a partial command or option and ++press Tab to finish it: ++ ++```text ++$ opc session li ++$ opc session list ++ ++$ opcr --att ++$ opcr --attach ++ ++$ opcc --log-l ++$ opcc --log-level ++``` ++ ++Candidates depend on your installed OpenCode version. In OpenCode 1.18.29, the ++CLI's completion output omits top-level TUI flags such as `--model` and `--fork`, ++even though those flags work when typed. Use `opencode --help` or ++`opencode run --help` for the full options, and see the ++[CLI reference](https://opencode.ai/docs/cli/) for more workflows. ++ ++## Aliases ++ ++| Alias | Command | Description | ++| ------ | --------------------- | ----------------------------------- | ++| `opc` | `opencode` | Launch the terminal UI | ++| `opcc` | `opencode --continue` | Continue the last session | ++| `opcr` | `opencode run` | Run a prompt without opening the UI | ++ ++To keep completion but skip the aliases, set this in your `.zshrc`, above the line ++that sources Oh My Zsh: ++ ++```zsh ++# ~/.zshrc ++zstyle ':omz:plugins:opencode' aliases no ++ ++plugins=(... opencode) ++ ++source $ZSH/oh-my-zsh.sh ++``` ++ ++## Common workflows ++ ++All aliases accept additional arguments: ++ ++```zsh ++# Open a project ++opc ~/projects/my-app ++ ++# Explore a different approach by forking the last session ++opcc --fork ++ ++# Ask a question without entering the terminal UI ++opcr "Explain the test setup in this project" ++ ++# Reuse an already running backend to avoid MCP server cold starts ++opcr --attach http://localhost:4096 "Explain this project's architecture" ++``` ++ ++## Completion ++ ++Completion queries the installed OpenCode CLI on demand for commands and options, ++including through the aliases above. It falls back to Zsh's default completion when ++the CLI returns no candidates. No OpenCode process is started at shell startup, ++and no generated completion cache is needed. ++ ++## Credits ++ ++Based on the OpenCode plugin proposals by ++[pranavavva](https://github.com/pranavavva) in ++[#13545](https://github.com/ohmyzsh/ohmyzsh/pull/13545) and ++[mskadu](https://github.com/mskadu) in ++[#13794](https://github.com/ohmyzsh/ohmyzsh/pull/13794). ++The completion adapter is derived from OpenCode's `opencode completion` output. +diff --git a/plugins/opencode/_opencode b/plugins/opencode/_opencode +new file mode 100644 +index 00000000..72e1410a +--- /dev/null ++++ b/plugins/opencode/_opencode +@@ -0,0 +1,12 @@ ++#compdef opencode ++ ++# Adapted from `opencode completion`, using the CLI's live Yargs completions. ++local -a reply ++reply=("${(@f)$(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" \ ++ command opencode --get-yargs-completions "${words[@]}" < /dev/null 2> /dev/null)}") ++ ++if [[ -n "${reply[1]}" ]]; then ++ _describe 'values' reply ++else ++ _default ++fi +diff --git a/plugins/opencode/opencode.plugin.zsh b/plugins/opencode/opencode.plugin.zsh +new file mode 100644 +index 00000000..a9227819 +--- /dev/null ++++ b/plugins/opencode/opencode.plugin.zsh +@@ -0,0 +1,7 @@ ++if (( ! $+commands[opencode] )); then ++ return ++fi ++ ++alias opc='opencode' ++alias opcc='opencode --continue' ++alias opcr='opencode run' diff --git a/tasks/ohmyzsh__ohmyzsh-14082/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14082/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14082/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14082/task.toml b/tasks/ohmyzsh__ohmyzsh-14082/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a1d6196eef8d81655bdf66af85c32efc3b141970 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14082/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14082" +description = "feat(opencode): add completion and opc aliases" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "d217d05374fc3c885d5fe304cea6606e2b22911a" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14082" +source_access = "auto" +built_at = "2026-11-16T16:09:56.868959+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:fcb6053ff11e881ad40544e7feddc2edaaae904006f910b06801da6876d61065" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-13T08:40:23Z" +diff_format = "unified" +context_files = [ + "plugins/opencode/README.md", + "plugins/opencode/_opencode", + "plugins/opencode/opencode.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 130 +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.985839+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:eaf7ccc4a98187695a04eff45a7feb76a542d8581cd906c856ed4e9764f89b9d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14082/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14082/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14082/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14082/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14082/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bf754cc1924231406d766a09da17f3f956f94918 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14082/tests/instruction.md @@ -0,0 +1,67 @@ +# Issue + +**Title:** feat(opencode): add completion and opc aliases + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [ ] The PR doesn’t replicate another PR which is already open. +- [ ] I have read the contribution guide and followed all the instructions. +- [ ] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it’s from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I’ve disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +Add a small plugin for the [OpenCode CLI](https://opencode.ai) with on-demand completion and three everyday aliases: + +| Alias | Command | Workflow | +| --- | --- | --- | +| `opc` | `opencode` | Open the terminal UI in the current or specified project | +| `opcc` | `opencode --continue` | Pick up the last session, optionally adding `--fork` | +| `opcr` | `opencode run` | Send a prompt without entering the UI, optionally attaching to an existing backend | + +The autoloaded completion function adapts the CLI-generated Yargs adapter and queries the installed CLI only when completing. No OpenCode process runs at shell startup and no generated completion cache is needed. Aliases are skipped silently when the CLI is absent and support the standard OMZ alias-disable style. + +The README emphasizes learning from tab completion, with command descriptions, partial-completion examples, and practical workflows. + +## Other comments: + +### Related contributions + +This is a proposed consolidation of #13545 by @pranavavva and #13794 by @mskadu. Thank you both for the initial completion integration and alias/workflow proposals. Both contributions are also credited in the README. + +This version uses the `opc` prefix, keeps the initial alias set small, and uses a separate autoloaded completion function instead of startup-time generation. Intended to supersede those proposals once reviewed and ready; neither is automatically closed by this PR. Feedback and testing from both authors would be welcome. + +The non-duplication checkbox is intentionally unchecked because this consolidates existing open proposals. Full contribution-guide compliance and wiki-style confirmation are left for maintainer review; contributor coordination and additional community testing remain outstanding. + +### Verification + +Tested with Zsh 5.9 and OpenCode 1.18.29: + +- Zsh syntax checks and Git whitespace checks pass. +- Real interactive Tab completion works for subcommands, nested session commands, global options, and run options through `opencode`, `opc`, `opcc`, and `opcr`. +- Alias expansion includes inserted `--continue` and `run` arguments in the completion context. +- Quoted arguments are forwarded through aliases. +- Missing CLI skips aliases silently and completion falls back to the default handler. +- Full Oh My Zsh loading with aliases disabled retains completion. +- No AI prompts or backend servers were launched during testing. + +### Known upstream limitations + +OpenCode 1.18.29 does not include default/TUI flags such as `--model` and `--fork` in its top-level completion output. Direct calls to its completion endpoint show the same limitation; the README documents it. The CLI also exposes a literal `$0` candidate and double-dash forms of short options. This adapter retains the upstream candidate list rather than maintaining a separate command schema. + +Additional community testing is welcome before merging. + +### AI assistance + +AI-assisted implementation, documentation, and testing using OpenCode. Attribution to the existing community proposals is preserved above and in the README. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d217d05374fc`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14082/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14082/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2e4380c16d2ea83316273329e233f9ab0e11be3d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14082/tests/oracle.patch @@ -0,0 +1,148 @@ +diff --git a/plugins/opencode/README.md b/plugins/opencode/README.md +new file mode 100644 +index 00000000..4766720c +--- /dev/null ++++ b/plugins/opencode/README.md +@@ -0,0 +1,111 @@ ++# opencode plugin ++ ++This plugin adds completion and aliases for the [OpenCode](https://opencode.ai) CLI. ++Install OpenCode using its [installation instructions](https://opencode.ai/docs/#install), ++and make sure `opencode` is available on your `$PATH`. ++ ++To enable it, add `opencode` to the plugins array in your `.zshrc`: ++ ++```zsh ++plugins=(... opencode) ++``` ++ ++## Learning OpenCode from the terminal ++ ++Use tab completion to explore commands and their descriptions without leaving the ++shell. For example, these are some of the candidates shown by the CLI: ++ ++```text ++$ opencode ++agent -- manage agents ++models -- list all available models ++run -- run opencode with a message ++session -- manage sessions ++stats -- show token usage and cost statistics ++... ++ ++$ opencode session ++delete -- delete a session ++list -- list sessions ++ ++$ opencode run -- ++--agent -- agent to use ++--continue -- continue the last session ++--file -- file(s) to attach to message ++--model -- model to use in the format of provider/model ++... ++``` ++ ++Completion works through the aliases too. Type a partial command or option and ++press Tab to finish it: ++ ++```text ++$ opc session li ++$ opc session list ++ ++$ opcr --att ++$ opcr --attach ++ ++$ opcc --log-l ++$ opcc --log-level ++``` ++ ++Candidates depend on your installed OpenCode version. In OpenCode 1.18.29, the ++CLI's completion output omits top-level TUI flags such as `--model` and `--fork`, ++even though those flags work when typed. Use `opencode --help` or ++`opencode run --help` for the full options, and see the ++[CLI reference](https://opencode.ai/docs/cli/) for more workflows. ++ ++## Aliases ++ ++| Alias | Command | Description | ++| ------ | --------------------- | ----------------------------------- | ++| `opc` | `opencode` | Launch the terminal UI | ++| `opcc` | `opencode --continue` | Continue the last session | ++| `opcr` | `opencode run` | Run a prompt without opening the UI | ++ ++To keep completion but skip the aliases, set this in your `.zshrc`, above the line ++that sources Oh My Zsh: ++ ++```zsh ++# ~/.zshrc ++zstyle ':omz:plugins:opencode' aliases no ++ ++plugins=(... opencode) ++ ++source $ZSH/oh-my-zsh.sh ++``` ++ ++## Common workflows ++ ++All aliases accept additional arguments: ++ ++```zsh ++# Open a project ++opc ~/projects/my-app ++ ++# Explore a different approach by forking the last session ++opcc --fork ++ ++# Ask a question without entering the terminal UI ++opcr "Explain the test setup in this project" ++ ++# Reuse an already running backend to avoid MCP server cold starts ++opcr --attach http://localhost:4096 "Explain this project's architecture" ++``` ++ ++## Completion ++ ++Completion queries the installed OpenCode CLI on demand for commands and options, ++including through the aliases above. It falls back to Zsh's default completion when ++the CLI returns no candidates. No OpenCode process is started at shell startup, ++and no generated completion cache is needed. ++ ++## Credits ++ ++Based on the OpenCode plugin proposals by ++[pranavavva](https://github.com/pranavavva) in ++[#13545](https://github.com/ohmyzsh/ohmyzsh/pull/13545) and ++[mskadu](https://github.com/mskadu) in ++[#13794](https://github.com/ohmyzsh/ohmyzsh/pull/13794). ++The completion adapter is derived from OpenCode's `opencode completion` output. +diff --git a/plugins/opencode/_opencode b/plugins/opencode/_opencode +new file mode 100644 +index 00000000..72e1410a +--- /dev/null ++++ b/plugins/opencode/_opencode +@@ -0,0 +1,12 @@ ++#compdef opencode ++ ++# Adapted from `opencode completion`, using the CLI's live Yargs completions. ++local -a reply ++reply=("${(@f)$(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" \ ++ command opencode --get-yargs-completions "${words[@]}" < /dev/null 2> /dev/null)}") ++ ++if [[ -n "${reply[1]}" ]]; then ++ _describe 'values' reply ++else ++ _default ++fi +diff --git a/plugins/opencode/opencode.plugin.zsh b/plugins/opencode/opencode.plugin.zsh +new file mode 100644 +index 00000000..a9227819 +--- /dev/null ++++ b/plugins/opencode/opencode.plugin.zsh +@@ -0,0 +1,7 @@ ++if (( ! $+commands[opencode] )); then ++ return ++fi ++ ++alias opc='opencode' ++alias opcc='opencode --continue' ++alias opcr='opencode run' diff --git a/tasks/ohmyzsh__ohmyzsh-14082/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14082/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..2503898203e390baffd445108bab7e5a59eabd30 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14082/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d217d05374fc3c885d5fe304cea6606e2b22911a > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14082/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14082/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14082/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14089/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14089/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7db2d36f3099a13888bfefa12d5eaff1555842a4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14089/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 68795c217069164e8dd31ae451512d7060bfc45c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 68795c217069164e8dd31ae451512d7060bfc45c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 68795c217069164e8dd31ae451512d7060bfc45c \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14089/instruction.md b/tasks/ohmyzsh__ohmyzsh-14089/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..09a916c76c1cf4687862fd735845dbdedfad9d96 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14089/instruction.md @@ -0,0 +1,44 @@ +# Issue + +**Title:** refactor(github)!: deprecate legacy hub plugin + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] This change does not introduce new aliases. + +## Changes: + +- Deprecate the `github` plugin, which supports the legacy `hub` CLI, and direct GitHub CLI users to the `gh` plugin. +- Keep existing `hub` behavior during the deprecation period while making the repository helpers use the current branch and stop after a failed directory change. +- Replace stale `github` documentation with migration guidance for `gh repo create`. +- Preserve the last valid `gh` completion cache when completion generation fails. +- Correct the documented `gh` completion cache location. + +## Testing: + +- Ran `zsh -n` against both plugin files. +- Ran `git diff --check`. +- Loaded both plugins through `oh-my-zsh.sh`. +- Generated and loaded completion using GitHub CLI v2.100.0. +- Simulated failed completion generation and verified the existing cache remained unchanged. +- Verified `exist_gh` does not call `hub` after a failed `cd` and pushes `HEAD` for a valid directory. + +## Other comments: + +GitHub CLI is not a drop-in Git wrapper, so this intentionally does not replace `alias git=hub` with `gh`. Existing `hub` users retain the old behavior until the deprecated plugin is removed. + +AI-assisted: OpenCode assisted with research, implementation, and test setup; the resulting changes were reviewed and tested manually. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `68795c217069`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14089/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14089/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c3ca3b4299d1b4937ac0751b74a12d0b570b0b04 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14089/solution/patch.diff @@ -0,0 +1,137 @@ +diff --git a/plugins/github/README.md b/plugins/github/README.md +index 5d8b6250..d24c21d1 100644 +--- a/plugins/github/README.md ++++ b/plugins/github/README.md +@@ -1,45 +1,43 @@ + # github plugin + +-This plugin supports working with GitHub from the command line. It provides a few things: ++> [!WARNING] ++> This plugin is deprecated and will be removed in a future release. It supports ++> the legacy [`hub`](https://github.com/mislav/hub) CLI, not the current GitHub ++> CLI. For `gh` completion, use the [`gh` plugin](../gh) instead. + +-* Sets up the `hub` wrapper and completions for the `git` command if you have [`hub`](https://github.com/github/hub) installed. +-* Completion for the [`github` Ruby gem](https://github.com/defunkt/github-gem). +-* Convenience functions for working with repos and URLs. ++The plugin provides compatibility for existing `hub` users by: + +-### Functions ++- aliasing `git` to `hub` when `hub` is installed; ++- adding completion for `hub`; and ++- defining convenience functions for creating repositories. + +-* `empty_gh` - Creates a new empty repo (with a `README.md`) and pushes it to GitHub +-* `new_gh` - Initializes an existing directory as a repo and pushes it to GitHub +-* `exist_gh` - Takes an existing repo and pushes it to GitHub ++## Migrating to GitHub CLI + ++Install [GitHub CLI](https://cli.github.com/), replace `github` with `gh` in ++your plugin list, and restart your shell: + +-## Installation +- +-[Hub](https://github.com/github/hub) needs to be installed if you want to use it. On OS X with Homebrew, this can be done with `brew install hub`. The `hub` completion definition needs to be added to your `$FPATH` before initializing OMZ. +- +-The [`github` Ruby gem](https://github.com/defunkt/github-gem) needs to be installed if you want to use it. +- +-### Configuration +- +-These settings affect `github`'s behavior. +- +-#### Environment variables ++```zsh ++plugins=(... gh) ++``` + +-* `$GITHUB_USER` +-* `$GITHUB_PASSWORD` ++The `gh` plugin supplies completion for the installed GitHub CLI. It does not ++alias `git`, because `gh` is not a Git wrapper. + +-#### Git configuration options ++The closest replacement for creating a GitHub repository from an existing ++local repository is: + +-* `github.user` - GitHub username for repo operations ++```zsh ++gh repo create --source=. --push ++``` + +-See `man hub` for more details. ++## Deprecated functions + +-### Homebrew installation note ++- `empty_gh` - creates a new repository with a `README.md` and pushes it to GitHub ++- `new_gh` - initializes an existing directory and pushes it to GitHub ++- `exist_gh` - pushes an existing Git repository to GitHub + +-If you have installed `hub` using Homebrew, its completions may not be on your `$FPATH` if you are using the system `zsh`. Homebrew installs `zsh` completion definitions to `/usr/local/share/zsh/site-functions`, which will be on `$FPATH` for the Homebrew-installed `zsh`, but not for the system `zsh`. If you want it to work with the system `zsh`, add this to your `~/.zshrc` before it sources `oh-my-zsh.sh`. ++These functions remain available during the deprecation period and require ++`hub`. They will be removed with the plugin. + +-```zsh +-if (( ! ${fpath[(I)/usr/local/share/zsh/site-functions]} )); then +- FPATH=/usr/local/share/zsh/site-functions:$FPATH +-fi +-``` ++If you continue using `hub`, see its documentation for authentication and ++configuration details. +diff --git a/plugins/github/github.plugin.zsh b/plugins/github/github.plugin.zsh +index 79114ff6..6f71cbf3 100644 +--- a/plugins/github/github.plugin.zsh ++++ b/plugins/github/github.plugin.zsh +@@ -1,3 +1,6 @@ ++print -Pru2 -- '%F{yellow}[oh-my-zsh] The %Bgithub%b plugin is deprecated and will be removed in a future release.' ++print -Pru2 -- 'It supports the legacy %Bhub%b CLI. Use the %Bgh%b plugin for GitHub CLI completion.%f' ++ + # Set up hub wrapper for git, if it is available; https://github.com/github/hub + if (( $+commands[hub] )); then + alias git=hub +@@ -26,7 +29,7 @@ empty_gh() { # [NAME_OF_REPO] + # This function will add all non-hidden files to git. + new_gh() { # [DIRECTORY] + emulate -L zsh +- local repo="$1" ++ local repo="${1-.}" + cd "$repo" \ + || return + +@@ -42,7 +45,7 @@ new_gh() { # [DIRECTORY] + || return + hub create \ + || return +- git push -u origin master \ ++ git push -u origin HEAD \ + || return + } + +@@ -52,18 +55,19 @@ new_gh() { # [DIRECTORY] + # to your GitHub. + exist_gh() { # [DIRECTORY] + emulate -L zsh +- local repo=$1 +- cd "$repo" ++ local repo="${1:-.}" ++ cd "$repo" \ ++ || return + + hub create \ + || return +- git push -u origin master ++ git push -u origin HEAD + } + + # git.io "GitHub URL" + # + # Shorten GitHub url, example: +-# https://github.com/nvogel/dotzsh > https://git.io/8nU25w ++# https://github.com/nvogel/dotzsh > https://git.io/8nU25w + # source: https://github.com/nvogel/dotzsh + # documentation: https://github.com/blog/985-git-io-github-url-shortener + # +@@ -74,4 +78,3 @@ git.io() { + } + + # End Functions ############################################################# +- diff --git a/tasks/ohmyzsh__ohmyzsh-14089/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14089/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14089/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14089/task.toml b/tasks/ohmyzsh__ohmyzsh-14089/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6a9e4fd586293eed210a928ca4eb1f13cf14a067 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14089/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14089" +description = "refactor(github)!: deprecate legacy hub plugin" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "68795c217069164e8dd31ae451512d7060bfc45c" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14089" +source_access = "auto" +built_at = "2026-11-16T16:09:56.909822+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c6606e52eec7484c83735eec358200bac2a942809c920e6e4a39526e2bb0a22d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-28T08:33:33Z" +diff_format = "unified" +context_files = [ + "plugins/github/README.md", + "plugins/github/github.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 77 +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.986338+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:9b3fd1d5b5424067a5f9e5d6a8e366248823dcfa0b4a1bae387fff7f5982542d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14089/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14089/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14089/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14089/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14089/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..09a916c76c1cf4687862fd735845dbdedfad9d96 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14089/tests/instruction.md @@ -0,0 +1,44 @@ +# Issue + +**Title:** refactor(github)!: deprecate legacy hub plugin + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] This change does not introduce new aliases. + +## Changes: + +- Deprecate the `github` plugin, which supports the legacy `hub` CLI, and direct GitHub CLI users to the `gh` plugin. +- Keep existing `hub` behavior during the deprecation period while making the repository helpers use the current branch and stop after a failed directory change. +- Replace stale `github` documentation with migration guidance for `gh repo create`. +- Preserve the last valid `gh` completion cache when completion generation fails. +- Correct the documented `gh` completion cache location. + +## Testing: + +- Ran `zsh -n` against both plugin files. +- Ran `git diff --check`. +- Loaded both plugins through `oh-my-zsh.sh`. +- Generated and loaded completion using GitHub CLI v2.100.0. +- Simulated failed completion generation and verified the existing cache remained unchanged. +- Verified `exist_gh` does not call `hub` after a failed `cd` and pushes `HEAD` for a valid directory. + +## Other comments: + +GitHub CLI is not a drop-in Git wrapper, so this intentionally does not replace `alias git=hub` with `gh`. Existing `hub` users retain the old behavior until the deprecated plugin is removed. + +AI-assisted: OpenCode assisted with research, implementation, and test setup; the resulting changes were reviewed and tested manually. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `68795c217069`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14089/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14089/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c3ca3b4299d1b4937ac0751b74a12d0b570b0b04 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14089/tests/oracle.patch @@ -0,0 +1,137 @@ +diff --git a/plugins/github/README.md b/plugins/github/README.md +index 5d8b6250..d24c21d1 100644 +--- a/plugins/github/README.md ++++ b/plugins/github/README.md +@@ -1,45 +1,43 @@ + # github plugin + +-This plugin supports working with GitHub from the command line. It provides a few things: ++> [!WARNING] ++> This plugin is deprecated and will be removed in a future release. It supports ++> the legacy [`hub`](https://github.com/mislav/hub) CLI, not the current GitHub ++> CLI. For `gh` completion, use the [`gh` plugin](../gh) instead. + +-* Sets up the `hub` wrapper and completions for the `git` command if you have [`hub`](https://github.com/github/hub) installed. +-* Completion for the [`github` Ruby gem](https://github.com/defunkt/github-gem). +-* Convenience functions for working with repos and URLs. ++The plugin provides compatibility for existing `hub` users by: + +-### Functions ++- aliasing `git` to `hub` when `hub` is installed; ++- adding completion for `hub`; and ++- defining convenience functions for creating repositories. + +-* `empty_gh` - Creates a new empty repo (with a `README.md`) and pushes it to GitHub +-* `new_gh` - Initializes an existing directory as a repo and pushes it to GitHub +-* `exist_gh` - Takes an existing repo and pushes it to GitHub ++## Migrating to GitHub CLI + ++Install [GitHub CLI](https://cli.github.com/), replace `github` with `gh` in ++your plugin list, and restart your shell: + +-## Installation +- +-[Hub](https://github.com/github/hub) needs to be installed if you want to use it. On OS X with Homebrew, this can be done with `brew install hub`. The `hub` completion definition needs to be added to your `$FPATH` before initializing OMZ. +- +-The [`github` Ruby gem](https://github.com/defunkt/github-gem) needs to be installed if you want to use it. +- +-### Configuration +- +-These settings affect `github`'s behavior. +- +-#### Environment variables ++```zsh ++plugins=(... gh) ++``` + +-* `$GITHUB_USER` +-* `$GITHUB_PASSWORD` ++The `gh` plugin supplies completion for the installed GitHub CLI. It does not ++alias `git`, because `gh` is not a Git wrapper. + +-#### Git configuration options ++The closest replacement for creating a GitHub repository from an existing ++local repository is: + +-* `github.user` - GitHub username for repo operations ++```zsh ++gh repo create --source=. --push ++``` + +-See `man hub` for more details. ++## Deprecated functions + +-### Homebrew installation note ++- `empty_gh` - creates a new repository with a `README.md` and pushes it to GitHub ++- `new_gh` - initializes an existing directory and pushes it to GitHub ++- `exist_gh` - pushes an existing Git repository to GitHub + +-If you have installed `hub` using Homebrew, its completions may not be on your `$FPATH` if you are using the system `zsh`. Homebrew installs `zsh` completion definitions to `/usr/local/share/zsh/site-functions`, which will be on `$FPATH` for the Homebrew-installed `zsh`, but not for the system `zsh`. If you want it to work with the system `zsh`, add this to your `~/.zshrc` before it sources `oh-my-zsh.sh`. ++These functions remain available during the deprecation period and require ++`hub`. They will be removed with the plugin. + +-```zsh +-if (( ! ${fpath[(I)/usr/local/share/zsh/site-functions]} )); then +- FPATH=/usr/local/share/zsh/site-functions:$FPATH +-fi +-``` ++If you continue using `hub`, see its documentation for authentication and ++configuration details. +diff --git a/plugins/github/github.plugin.zsh b/plugins/github/github.plugin.zsh +index 79114ff6..6f71cbf3 100644 +--- a/plugins/github/github.plugin.zsh ++++ b/plugins/github/github.plugin.zsh +@@ -1,3 +1,6 @@ ++print -Pru2 -- '%F{yellow}[oh-my-zsh] The %Bgithub%b plugin is deprecated and will be removed in a future release.' ++print -Pru2 -- 'It supports the legacy %Bhub%b CLI. Use the %Bgh%b plugin for GitHub CLI completion.%f' ++ + # Set up hub wrapper for git, if it is available; https://github.com/github/hub + if (( $+commands[hub] )); then + alias git=hub +@@ -26,7 +29,7 @@ empty_gh() { # [NAME_OF_REPO] + # This function will add all non-hidden files to git. + new_gh() { # [DIRECTORY] + emulate -L zsh +- local repo="$1" ++ local repo="${1-.}" + cd "$repo" \ + || return + +@@ -42,7 +45,7 @@ new_gh() { # [DIRECTORY] + || return + hub create \ + || return +- git push -u origin master \ ++ git push -u origin HEAD \ + || return + } + +@@ -52,18 +55,19 @@ new_gh() { # [DIRECTORY] + # to your GitHub. + exist_gh() { # [DIRECTORY] + emulate -L zsh +- local repo=$1 +- cd "$repo" ++ local repo="${1:-.}" ++ cd "$repo" \ ++ || return + + hub create \ + || return +- git push -u origin master ++ git push -u origin HEAD + } + + # git.io "GitHub URL" + # + # Shorten GitHub url, example: +-# https://github.com/nvogel/dotzsh > https://git.io/8nU25w ++# https://github.com/nvogel/dotzsh > https://git.io/8nU25w + # source: https://github.com/nvogel/dotzsh + # documentation: https://github.com/blog/985-git-io-github-url-shortener + # +@@ -74,4 +78,3 @@ git.io() { + } + + # End Functions ############################################################# +- diff --git a/tasks/ohmyzsh__ohmyzsh-14089/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14089/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..87dbb3b25c91c79629bc8aab1c898159821716af --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14089/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 68795c217069164e8dd31ae451512d7060bfc45c > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14089/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14089/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14089/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14091/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14091/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8ed063bd29b9f79697d5340f2e6f8ad92479c1e0 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14091/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin c6e66edee824d83e84473ec666917b58323630df 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard c6e66edee824d83e84473ec666917b58323630df \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base c6e66edee824d83e84473ec666917b58323630df \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14091/instruction.md b/tasks/ohmyzsh__ohmyzsh-14091/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cab2e55f7805ebc53a19dfe98ad45c5ef1eb238b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14091/instruction.md @@ -0,0 +1,41 @@ +# Issue + +**Title:** fix(emacs): create a frame for empty launcher invocations + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or from somewhere with an MIT-compatible license. +- [x] Meaningful AI assistance is disclosed below. +- [x] The code is efficient and does not waste computer resources. +- [x] The code was tested as described below. +- [x] No new aliases are introduced. + +## Changes: + +, following @robbyrussell's diagnosis in the issue. + +With a GUI frame already open, bare `emacs`/`e` passes only `--no-wait` to emacsclient and fails with “file name or argument required”. Route an empty invocation, or the single `--no-wait` argument added by those aliases, through the existing `--create-frame` branch. + +Add a standalone regression script covering those calls, existing/missing frames, quoted file arguments, Lisp evaluation, terminal options from #14055, and client exit status. + +## Other comments: + +Validation: +- The new regression fails on unmodified master because `--create-frame` is missing. +- All 13 checks pass with sh, bash, dash, and zsh as the launcher shell (52 checks). Run `sh plugins/emacs/tests/emacsclient.sh`; set `TEST_SHELL` to choose another shell. +- The actual `emacs` and `e` aliases were also tested in isolated `zsh -df` processes. +- The upstream CI syntax check passes for all 585 files; both changed scripts parse in all four shells; `git diff --check` passes. + +Tests use an emacsclient stub that returns an existing frame and records arguments; no real Emacs GUI was launched. + +AI-assisted: OpenAI Codex (GPT-6) implemented the change and regression tests and ran the validation above. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c6e66edee824`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14091/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14091/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..55b9d654e40ab66d0b82c95796f90a35d37b5cdc --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14091/solution/patch.diff @@ -0,0 +1,16 @@ +diff --git a/plugins/emacs/emacsclient.sh b/plugins/emacs/emacsclient.sh +index 208eec71..57626c2e 100755 +--- a/plugins/emacs/emacsclient.sh ++++ b/plugins/emacs/emacsclient.sh +@@ -32,8 +32,9 @@ emacsfun() { + # Check if there are suitable frames + frames="$(emacsclient -a '' -n -e "$cmd" 2>/dev/null |sed 's/.*\x07//g' )" + +- # Only create another X frame if there isn't one present +- if [ -z "$frames" -o "$frames" = nil ]; then ++ # A bare emacs/e passes only --no-wait, so it still needs --create-frame. ++ if [ -z "$frames" ] || [ "$frames" = nil ] || [ "$#" -eq 0 ] \ ++ || { [ "$#" -eq 1 ] && [ "$1" = --no-wait ]; }; then + emacsclient --alternate-editor="" --create-frame "$@" + return $? + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14091/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14091/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14091/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14091/task.toml b/tasks/ohmyzsh__ohmyzsh-14091/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..830c48b16ad360771a190d89728203e1712bd145 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14091/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14091" +description = "fix(emacs): create a frame for empty launcher invocations" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "c6e66edee824d83e84473ec666917b58323630df" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14091" +source_access = "auto" +built_at = "2026-11-16T16:09:56.902948+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:111cd3ca3fc4b59d0e4cf75470ac9c1f037d1239da979e792bcf87c398d9b781" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-28T07:41:07Z" +diff_format = "unified" +context_files = [ + "plugins/emacs/emacsclient.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.986833+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:fb1cf32a454ec83f477d8795512eab2d9c15f67c658edf1f7750722eafccd082" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14091/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14091/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14091/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14091/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14091/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cab2e55f7805ebc53a19dfe98ad45c5ef1eb238b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14091/tests/instruction.md @@ -0,0 +1,41 @@ +# Issue + +**Title:** fix(emacs): create a frame for empty launcher invocations + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or from somewhere with an MIT-compatible license. +- [x] Meaningful AI assistance is disclosed below. +- [x] The code is efficient and does not waste computer resources. +- [x] The code was tested as described below. +- [x] No new aliases are introduced. + +## Changes: + +, following @robbyrussell's diagnosis in the issue. + +With a GUI frame already open, bare `emacs`/`e` passes only `--no-wait` to emacsclient and fails with “file name or argument required”. Route an empty invocation, or the single `--no-wait` argument added by those aliases, through the existing `--create-frame` branch. + +Add a standalone regression script covering those calls, existing/missing frames, quoted file arguments, Lisp evaluation, terminal options from #14055, and client exit status. + +## Other comments: + +Validation: +- The new regression fails on unmodified master because `--create-frame` is missing. +- All 13 checks pass with sh, bash, dash, and zsh as the launcher shell (52 checks). Run `sh plugins/emacs/tests/emacsclient.sh`; set `TEST_SHELL` to choose another shell. +- The actual `emacs` and `e` aliases were also tested in isolated `zsh -df` processes. +- The upstream CI syntax check passes for all 585 files; both changed scripts parse in all four shells; `git diff --check` passes. + +Tests use an emacsclient stub that returns an existing frame and records arguments; no real Emacs GUI was launched. + +AI-assisted: OpenAI Codex (GPT-6) implemented the change and regression tests and ran the validation above. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `c6e66edee824`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14091/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14091/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..55b9d654e40ab66d0b82c95796f90a35d37b5cdc --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14091/tests/oracle.patch @@ -0,0 +1,16 @@ +diff --git a/plugins/emacs/emacsclient.sh b/plugins/emacs/emacsclient.sh +index 208eec71..57626c2e 100755 +--- a/plugins/emacs/emacsclient.sh ++++ b/plugins/emacs/emacsclient.sh +@@ -32,8 +32,9 @@ emacsfun() { + # Check if there are suitable frames + frames="$(emacsclient -a '' -n -e "$cmd" 2>/dev/null |sed 's/.*\x07//g' )" + +- # Only create another X frame if there isn't one present +- if [ -z "$frames" -o "$frames" = nil ]; then ++ # A bare emacs/e passes only --no-wait, so it still needs --create-frame. ++ if [ -z "$frames" ] || [ "$frames" = nil ] || [ "$#" -eq 0 ] \ ++ || { [ "$#" -eq 1 ] && [ "$1" = --no-wait ]; }; then + emacsclient --alternate-editor="" --create-frame "$@" + return $? + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14091/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14091/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9cb1ec81fcb817282477f7b37d434bbf25dd4986 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14091/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace c6e66edee824d83e84473ec666917b58323630df > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14091/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14091/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14091/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14092/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14092/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..eef03ba4fa6f5944c7efca16ae807addec6a1a14 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14092/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin be8da5c77192eb3da3699ea7c5e47bdfaa5eea4e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard be8da5c77192eb3da3699ea7c5e47bdfaa5eea4e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base be8da5c77192eb3da3699ea7c5e47bdfaa5eea4e \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14092/instruction.md b/tasks/ohmyzsh__ohmyzsh-14092/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1e14b25fb966b7a2df6e2e34c63e8b1ef2a46363 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14092/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** fix(globalias): preserve quoted words and assignment values + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. (No new aliases.) + +## Changes: + +With `alias 1='cd -1'`, typing `DEBUG=1` and pressing space changes the buffer to `DEBUG=cd -1 `. Quoting the value doesn't prevent it. `_expand_alias` sees the assignment value as a completion word, so the existing shell-word parsing alone doesn't protect it. + +Only call `_expand_alias` when the complete, unmodified shell word is present in `aliases` or `galiases`. Assignment values and quoted words are then left to the existing `expand-word` widget. Ordinary/global aliases, filtered values, arithmetic and glob expansion continue to work. + +. + +## Other comments: + +Added a standalone regression test using zsh's `zpty` and the real ZLE widgets, without external test dependencies: + +```sh +zsh plugins/globalias/tests/globalias.test.zsh +``` + +On macOS with zsh 5.9, the unmodified plugin fails the first `DEBUG=1` assertion; the patch passes all 13 cases. Syntax checks and `git diff --check` also pass. + +Related: #13708 addresses a backslash-prefixed word by skipping all expansion. This also preserves escaped aliases, but addresses the reported assignment and quoted-word corruption while retaining the separate word-expansion step. + +AI-assisted: OpenAI Codex helped implement the fix and regression tests and ran the checks above. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `be8da5c77192`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14092/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14092/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2f65c4f53ff91aeb0472317748fcba187984c713 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14092/solution/patch.diff @@ -0,0 +1,104 @@ +diff --git a/plugins/globalias/globalias.plugin.zsh b/plugins/globalias/globalias.plugin.zsh +index bd27d589..cfcb5bae 100644 +--- a/plugins/globalias/globalias.plugin.zsh ++++ b/plugins/globalias/globalias.plugin.zsh +@@ -4,7 +4,11 @@ globalias() { + # (A) makes it an array even if there's only one element + local word=${${(Az)LBUFFER}[-1]} + if [[ $GLOBALIAS_FILTER_VALUES[(Ie)$word] -eq 0 ]]; then +- zle _expand_alias ++ # Completion also considers quoted strings and assignment values as aliases. ++ # Only expand when the complete shell word is an alias name. ++ if (( ${+aliases[$word]} || ${+galiases[$word]} )); then ++ zle _expand_alias ++ fi + zle expand-word + fi + zle self-insert +diff --git a/plugins/globalias/tests/globalias.test.zsh b/plugins/globalias/tests/globalias.test.zsh +new file mode 100644 +index 00000000..c5a0e39b +--- /dev/null ++++ b/plugins/globalias/tests/globalias.test.zsh +@@ -0,0 +1,81 @@ ++#!/usr/bin/env zsh ++ ++# Exercise the actual ZLE widgets in an isolated interactive shell. ++emulate -L zsh ++setopt err_return ++zmodload zsh/zpty ++zmodload zsh/zselect ++ ++local test_dir=$(mktemp -d) ++export GLOBALIAS_TEST_PLUGIN=${0:A:h:h}/globalias.plugin.zsh ++export GLOBALIAS_TEST_RESULT=$test_dir/result ++ ++wait_for_marker() { ++ local marker=$1 output received ++ local -i deadline=$(( SECONDS + 5 )) ++ while (( SECONDS < deadline )); do ++ if zpty -r globalias-test output; then ++ received+=$output ++ [[ $received == *$marker* ]] && return 0 ++ else ++ zselect -t 1 || true ++ fi ++ done ++ print -u2 -r -- "Timed out waiting for ZLE: $received" ++ return 1 ++} ++ ++check_expansion() { ++ local input=$1 expected=$2 actual ++ zpty -w -n globalias-test "$input"$' \x18' ++ wait_for_marker GLOBALIAS_TEST_CAPTURED ++ actual=$(< "$GLOBALIAS_TEST_RESULT") ++ if [[ $actual != "$expected" ]]; then ++ print -u2 -r -- "Input: ${(qqq)input}" ++ print -u2 -r -- "Expected: ${(qqq)expected}; got: ${(qqq)actual}" ++ return 1 ++ fi ++} ++ ++{ ++ cat > "$test_dir/setup.zsh" <<'SETUP' ++autoload -Uz compinit ++compinit -D ++source "$GLOBALIAS_TEST_PLUGIN" ++alias 1='cd -1' ++alias ll='ls -l' ++alias -g G='| grep' ++GLOBALIAS_FILTER_VALUES=(ll) ++_globalias_test_capture() { ++ print -rn -- "$BUFFER" > "$GLOBALIAS_TEST_RESULT" ++ print -r -- $'\nGLOBALIAS_TEST_CAPTURED' ++ BUFFER= ++ zle .accept-line ++} ++zle -N _globalias_test_capture ++bindkey '^X' _globalias_test_capture ++PS1='GLOBALIAS_TEST_READY> ' ++RPROMPT= ++SETUP ++ zpty -b globalias-test zsh -dfi ++ zpty -w globalias-test "source ${(q)test_dir}/setup.zsh" ++ wait_for_marker GLOBALIAS_TEST_READY ++ ++ check_expansion 'DEBUG=1' 'DEBUG=1 ' ++ check_expansion 'DEBUG="1"' 'DEBUG="1" ' ++ check_expansion "DEBUG='1'" "DEBUG='1' " ++ check_expansion '1' 'cd -1 ' ++ check_expansion '"1"' '"1" ' ++ check_expansion "'1'" "'1' " ++ check_expansion '\1' '\1 ' ++ check_expansion 'echo G' 'echo | grep ' ++ check_expansion 'DEBUG=1 1' 'DEBUG=1 cd -1 ' ++ check_expansion 'll' 'll ' ++ check_expansion 'echo $((1+2))' 'echo 3 ' ++ check_expansion 'echo {a,b}' 'echo a b ' ++ check_expansion '' ' ' ++ print 'All globalias expansion tests passed.' ++} always { ++ zpty -d globalias-test 2>/dev/null || true ++ rm -rf -- "$test_dir" ++} diff --git a/tasks/ohmyzsh__ohmyzsh-14092/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14092/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14092/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14092/task.toml b/tasks/ohmyzsh__ohmyzsh-14092/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4e34418a2f4e3fc2af60eebca52333686ac34509 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14092/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14092" +description = "fix(globalias): preserve quoted words and assignment values" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "be8da5c77192eb3da3699ea7c5e47bdfaa5eea4e" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14092" +source_access = "auto" +built_at = "2026-11-16T16:09:56.883090+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:10f3a76c142cab6df549aae83f13edca3b8ae526b36f4d57ad6f83fd01fe41a5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-11T22:58:22Z" +diff_format = "unified" +context_files = [ + "plugins/globalias/globalias.plugin.zsh", + "plugins/globalias/tests/globalias.test.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 87 +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.987336+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8b23339a148ba2b1c2c06f9c1f80106bc0941ff4f17f22e4a1fd3d9cbe8ee0c6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14092/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14092/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14092/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14092/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14092/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1e14b25fb966b7a2df6e2e34c63e8b1ef2a46363 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14092/tests/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** fix(globalias): preserve quoted words and assignment values + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. (No new aliases.) + +## Changes: + +With `alias 1='cd -1'`, typing `DEBUG=1` and pressing space changes the buffer to `DEBUG=cd -1 `. Quoting the value doesn't prevent it. `_expand_alias` sees the assignment value as a completion word, so the existing shell-word parsing alone doesn't protect it. + +Only call `_expand_alias` when the complete, unmodified shell word is present in `aliases` or `galiases`. Assignment values and quoted words are then left to the existing `expand-word` widget. Ordinary/global aliases, filtered values, arithmetic and glob expansion continue to work. + +. + +## Other comments: + +Added a standalone regression test using zsh's `zpty` and the real ZLE widgets, without external test dependencies: + +```sh +zsh plugins/globalias/tests/globalias.test.zsh +``` + +On macOS with zsh 5.9, the unmodified plugin fails the first `DEBUG=1` assertion; the patch passes all 13 cases. Syntax checks and `git diff --check` also pass. + +Related: #13708 addresses a backslash-prefixed word by skipping all expansion. This also preserves escaped aliases, but addresses the reported assignment and quoted-word corruption while retaining the separate word-expansion step. + +AI-assisted: OpenAI Codex helped implement the fix and regression tests and ran the checks above. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `be8da5c77192`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14092/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14092/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2f65c4f53ff91aeb0472317748fcba187984c713 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14092/tests/oracle.patch @@ -0,0 +1,104 @@ +diff --git a/plugins/globalias/globalias.plugin.zsh b/plugins/globalias/globalias.plugin.zsh +index bd27d589..cfcb5bae 100644 +--- a/plugins/globalias/globalias.plugin.zsh ++++ b/plugins/globalias/globalias.plugin.zsh +@@ -4,7 +4,11 @@ globalias() { + # (A) makes it an array even if there's only one element + local word=${${(Az)LBUFFER}[-1]} + if [[ $GLOBALIAS_FILTER_VALUES[(Ie)$word] -eq 0 ]]; then +- zle _expand_alias ++ # Completion also considers quoted strings and assignment values as aliases. ++ # Only expand when the complete shell word is an alias name. ++ if (( ${+aliases[$word]} || ${+galiases[$word]} )); then ++ zle _expand_alias ++ fi + zle expand-word + fi + zle self-insert +diff --git a/plugins/globalias/tests/globalias.test.zsh b/plugins/globalias/tests/globalias.test.zsh +new file mode 100644 +index 00000000..c5a0e39b +--- /dev/null ++++ b/plugins/globalias/tests/globalias.test.zsh +@@ -0,0 +1,81 @@ ++#!/usr/bin/env zsh ++ ++# Exercise the actual ZLE widgets in an isolated interactive shell. ++emulate -L zsh ++setopt err_return ++zmodload zsh/zpty ++zmodload zsh/zselect ++ ++local test_dir=$(mktemp -d) ++export GLOBALIAS_TEST_PLUGIN=${0:A:h:h}/globalias.plugin.zsh ++export GLOBALIAS_TEST_RESULT=$test_dir/result ++ ++wait_for_marker() { ++ local marker=$1 output received ++ local -i deadline=$(( SECONDS + 5 )) ++ while (( SECONDS < deadline )); do ++ if zpty -r globalias-test output; then ++ received+=$output ++ [[ $received == *$marker* ]] && return 0 ++ else ++ zselect -t 1 || true ++ fi ++ done ++ print -u2 -r -- "Timed out waiting for ZLE: $received" ++ return 1 ++} ++ ++check_expansion() { ++ local input=$1 expected=$2 actual ++ zpty -w -n globalias-test "$input"$' \x18' ++ wait_for_marker GLOBALIAS_TEST_CAPTURED ++ actual=$(< "$GLOBALIAS_TEST_RESULT") ++ if [[ $actual != "$expected" ]]; then ++ print -u2 -r -- "Input: ${(qqq)input}" ++ print -u2 -r -- "Expected: ${(qqq)expected}; got: ${(qqq)actual}" ++ return 1 ++ fi ++} ++ ++{ ++ cat > "$test_dir/setup.zsh" <<'SETUP' ++autoload -Uz compinit ++compinit -D ++source "$GLOBALIAS_TEST_PLUGIN" ++alias 1='cd -1' ++alias ll='ls -l' ++alias -g G='| grep' ++GLOBALIAS_FILTER_VALUES=(ll) ++_globalias_test_capture() { ++ print -rn -- "$BUFFER" > "$GLOBALIAS_TEST_RESULT" ++ print -r -- $'\nGLOBALIAS_TEST_CAPTURED' ++ BUFFER= ++ zle .accept-line ++} ++zle -N _globalias_test_capture ++bindkey '^X' _globalias_test_capture ++PS1='GLOBALIAS_TEST_READY> ' ++RPROMPT= ++SETUP ++ zpty -b globalias-test zsh -dfi ++ zpty -w globalias-test "source ${(q)test_dir}/setup.zsh" ++ wait_for_marker GLOBALIAS_TEST_READY ++ ++ check_expansion 'DEBUG=1' 'DEBUG=1 ' ++ check_expansion 'DEBUG="1"' 'DEBUG="1" ' ++ check_expansion "DEBUG='1'" "DEBUG='1' " ++ check_expansion '1' 'cd -1 ' ++ check_expansion '"1"' '"1" ' ++ check_expansion "'1'" "'1' " ++ check_expansion '\1' '\1 ' ++ check_expansion 'echo G' 'echo | grep ' ++ check_expansion 'DEBUG=1 1' 'DEBUG=1 cd -1 ' ++ check_expansion 'll' 'll ' ++ check_expansion 'echo $((1+2))' 'echo 3 ' ++ check_expansion 'echo {a,b}' 'echo a b ' ++ check_expansion '' ' ' ++ print 'All globalias expansion tests passed.' ++} always { ++ zpty -d globalias-test 2>/dev/null || true ++ rm -rf -- "$test_dir" ++} diff --git a/tasks/ohmyzsh__ohmyzsh-14092/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14092/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41dc12edcd02ef563a439532e17921e88eabe10d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14092/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace be8da5c77192eb3da3699ea7c5e47bdfaa5eea4e > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14092/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14092/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14092/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14094/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14094/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..eef03ba4fa6f5944c7efca16ae807addec6a1a14 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14094/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin be8da5c77192eb3da3699ea7c5e47bdfaa5eea4e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard be8da5c77192eb3da3699ea7c5e47bdfaa5eea4e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base be8da5c77192eb3da3699ea7c5e47bdfaa5eea4e \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14094/instruction.md b/tasks/ohmyzsh__ohmyzsh-14094/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2ad6640b9bc441b70056d9f8bf6f476ab023ca0b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14094/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** chore(kube-ps1): update to version b4cd09ec + +## Description + +## Description + +Update for **kube-ps1 plugin**: update to version . +Check out the [list of changes](https://github.com/jonmosco/kube-ps1/compare/jonmosco:04af46f...jonmosco:b4cd09e). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `be8da5c77192`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14094/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14094/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..1f35bef882bdce5a822fe748509de9925bd72b92 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14094/solution/patch.diff @@ -0,0 +1,94 @@ +diff --git a/.github/dependencies.yml b/.github/dependencies.yml +index 2c33dd28..5bd06bb3 100644 +--- a/.github/dependencies.yml ++++ b/.github/dependencies.yml +@@ -30,7 +30,7 @@ dependencies: + plugins/kube-ps1: + repo: jonmosco/kube-ps1 + branch: master +- version: 04af46f7fe888ad287abcab6699b9bb10234bc3d ++ version: b4cd09ec8d4dc007173e28da40aeebf8eff8c87f + precopy: | + set -e + find . ! -name kube-ps1.sh ! -name LICENSE ! -name README.md -delete +diff --git a/plugins/kube-ps1/kube-ps1.plugin.zsh b/plugins/kube-ps1/kube-ps1.plugin.zsh +index 6d81e483..762b65c1 100644 +--- a/plugins/kube-ps1/kube-ps1.plugin.zsh ++++ b/plugins/kube-ps1/kube-ps1.plugin.zsh +@@ -1,6 +1,6 @@ + #!/usr/bin/env bash + +-# Kubernetes prompt helper for bash/zsh ++# Kubernetes prompt info for bash, fish, and zsh + # Displays current context and namespace + + # Copyright 2026 Jon Mosco +@@ -121,7 +121,7 @@ _kube_ps1_color_fg() { + if [[ "${_KUBE_PS1_TPUT_AVAILABLE}" == "true" ]]; then + _KUBE_PS1_FG_CODE="$(tput setaf "${_KUBE_PS1_FG_CODE}")" + elif [[ $_KUBE_PS1_FG_CODE -ge 0 ]] && [[ $_KUBE_PS1_FG_CODE -le 255 ]]; then +- _KUBE_PS1_FG_CODE="\033[38;5;${_KUBE_PS1_FG_CODE}m" ++ _KUBE_PS1_FG_CODE=$'\033'"[38;5;${_KUBE_PS1_FG_CODE}m" + else + _KUBE_PS1_FG_CODE="${_KUBE_PS1_DEFAULT_FG}" + fi +@@ -154,7 +154,7 @@ _kube_ps1_color_bg() { + if [[ "${_KUBE_PS1_TPUT_AVAILABLE}" == "true" ]]; then + _KUBE_PS1_BG_CODE="$(tput setab "${_KUBE_PS1_BG_CODE}")" + elif [[ $_KUBE_PS1_BG_CODE -ge 0 ]] && [[ $_KUBE_PS1_BG_CODE -le 255 ]]; then +- _KUBE_PS1_BG_CODE="\033[48;5;${_KUBE_PS1_BG_CODE}m" ++ _KUBE_PS1_BG_CODE=$'\033'"[48;5;${_KUBE_PS1_BG_CODE}m" + else + _KUBE_PS1_BG_CODE="${_KUBE_PS1_DEFAULT_BG}" + fi +@@ -412,6 +412,8 @@ kube_ps1() { + + local KUBE_PS1 + local KUBE_PS1_RESET_COLOR="${_KUBE_PS1_OPEN_ESC}${_KUBE_PS1_DEFAULT_FG}${_KUBE_PS1_CLOSE_ESC}" ++ local ctx_color="${KUBE_PS1_CTX_COLOR-red}" ++ local ns_color="${KUBE_PS1_NS_COLOR-cyan}" + + # Background Color + [[ -n "${KUBE_PS1_BG_COLOR}" ]] && KUBE_PS1+="$(_kube_ps1_color_bg "${KUBE_PS1_BG_COLOR}")" +@@ -432,22 +434,29 @@ kube_ps1() { + + # Context + if [[ "${KUBE_PS1_CONTEXT_ENABLE}" == true ]]; then +- local ctx_color="${KUBE_PS1_CTX_COLOR:-red}" +- + # Allow custom function to override color based on context + if [[ -n "${KUBE_PS1_CTX_COLOR_FUNCTION}" ]]; then + ctx_color="$("${KUBE_PS1_CTX_COLOR_FUNCTION}" "${KUBE_PS1_CONTEXT}")" + fi + +- KUBE_PS1+="$(_kube_ps1_color_fg "${ctx_color}")${KUBE_PS1_CONTEXT}${KUBE_PS1_RESET_COLOR}" ++ if [[ -n "${ctx_color}" ]]; then ++ KUBE_PS1+="$(_kube_ps1_color_fg "${ctx_color}")${KUBE_PS1_CONTEXT}${KUBE_PS1_RESET_COLOR}" ++ else ++ KUBE_PS1+="${KUBE_PS1_CONTEXT}" ++ fi + fi + + # Namespace + if [[ "${KUBE_PS1_NS_ENABLE}" == true ]]; then +- if [[ -n "${KUBE_PS1_DIVIDER}" ]] && [[ "${KUBE_PS1_CONTEXT_ENABLE}" == true ]]; then ++ if [[ -n "${KUBE_PS1_DIVIDER}" && "${KUBE_PS1_CONTEXT_ENABLE}" == true ]]; then + KUBE_PS1+="${KUBE_PS1_DIVIDER}" + fi +- KUBE_PS1+="$(_kube_ps1_color_fg "${KUBE_PS1_NS_COLOR:-cyan}")${KUBE_PS1_NAMESPACE}${KUBE_PS1_RESET_COLOR}" ++ ++ if [[ -n "${ns_color}" ]]; then ++ KUBE_PS1+="$(_kube_ps1_color_fg "${ns_color}")${KUBE_PS1_NAMESPACE}${KUBE_PS1_RESET_COLOR}" ++ else ++ KUBE_PS1+="${KUBE_PS1_NAMESPACE}" ++ fi + fi + + # Suffix +@@ -460,5 +469,5 @@ kube_ps1() { + # Close Background color if defined + [[ -n "${KUBE_PS1_BG_COLOR}" ]] && KUBE_PS1+="${_KUBE_PS1_OPEN_ESC}${_KUBE_PS1_DEFAULT_BG}${_KUBE_PS1_CLOSE_ESC}" + +- echo "${KUBE_PS1}" ++ printf '%s' "${KUBE_PS1}" + } diff --git a/tasks/ohmyzsh__ohmyzsh-14094/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14094/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14094/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14094/task.toml b/tasks/ohmyzsh__ohmyzsh-14094/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..46345fe7960f60d43569f259b68a21681d9867af --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14094/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14094" +description = "chore(kube-ps1): update to version b4cd09ec" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "be8da5c77192eb3da3699ea7c5e47bdfaa5eea4e" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14094" +source_access = "auto" +built_at = "2026-11-16T16:09:56.960080+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b1171039d08a1e047b10fa073d0b352f827a4e30d11c5de24f8d3fc720373dbb" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-14T10:03:38Z" +diff_format = "unified" +context_files = [ + ".github/dependencies.yml", + "plugins/kube-ps1/kube-ps1.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 29 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.987906+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8b23339a148ba2b1c2c06f9c1f80106bc0941ff4f17f22e4a1fd3d9cbe8ee0c6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14094/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14094/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14094/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14094/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14094/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2ad6640b9bc441b70056d9f8bf6f476ab023ca0b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14094/tests/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** chore(kube-ps1): update to version b4cd09ec + +## Description + +## Description + +Update for **kube-ps1 plugin**: update to version . +Check out the [list of changes](https://github.com/jonmosco/kube-ps1/compare/jonmosco:04af46f...jonmosco:b4cd09e). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `be8da5c77192`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14094/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14094/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..1f35bef882bdce5a822fe748509de9925bd72b92 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14094/tests/oracle.patch @@ -0,0 +1,94 @@ +diff --git a/.github/dependencies.yml b/.github/dependencies.yml +index 2c33dd28..5bd06bb3 100644 +--- a/.github/dependencies.yml ++++ b/.github/dependencies.yml +@@ -30,7 +30,7 @@ dependencies: + plugins/kube-ps1: + repo: jonmosco/kube-ps1 + branch: master +- version: 04af46f7fe888ad287abcab6699b9bb10234bc3d ++ version: b4cd09ec8d4dc007173e28da40aeebf8eff8c87f + precopy: | + set -e + find . ! -name kube-ps1.sh ! -name LICENSE ! -name README.md -delete +diff --git a/plugins/kube-ps1/kube-ps1.plugin.zsh b/plugins/kube-ps1/kube-ps1.plugin.zsh +index 6d81e483..762b65c1 100644 +--- a/plugins/kube-ps1/kube-ps1.plugin.zsh ++++ b/plugins/kube-ps1/kube-ps1.plugin.zsh +@@ -1,6 +1,6 @@ + #!/usr/bin/env bash + +-# Kubernetes prompt helper for bash/zsh ++# Kubernetes prompt info for bash, fish, and zsh + # Displays current context and namespace + + # Copyright 2026 Jon Mosco +@@ -121,7 +121,7 @@ _kube_ps1_color_fg() { + if [[ "${_KUBE_PS1_TPUT_AVAILABLE}" == "true" ]]; then + _KUBE_PS1_FG_CODE="$(tput setaf "${_KUBE_PS1_FG_CODE}")" + elif [[ $_KUBE_PS1_FG_CODE -ge 0 ]] && [[ $_KUBE_PS1_FG_CODE -le 255 ]]; then +- _KUBE_PS1_FG_CODE="\033[38;5;${_KUBE_PS1_FG_CODE}m" ++ _KUBE_PS1_FG_CODE=$'\033'"[38;5;${_KUBE_PS1_FG_CODE}m" + else + _KUBE_PS1_FG_CODE="${_KUBE_PS1_DEFAULT_FG}" + fi +@@ -154,7 +154,7 @@ _kube_ps1_color_bg() { + if [[ "${_KUBE_PS1_TPUT_AVAILABLE}" == "true" ]]; then + _KUBE_PS1_BG_CODE="$(tput setab "${_KUBE_PS1_BG_CODE}")" + elif [[ $_KUBE_PS1_BG_CODE -ge 0 ]] && [[ $_KUBE_PS1_BG_CODE -le 255 ]]; then +- _KUBE_PS1_BG_CODE="\033[48;5;${_KUBE_PS1_BG_CODE}m" ++ _KUBE_PS1_BG_CODE=$'\033'"[48;5;${_KUBE_PS1_BG_CODE}m" + else + _KUBE_PS1_BG_CODE="${_KUBE_PS1_DEFAULT_BG}" + fi +@@ -412,6 +412,8 @@ kube_ps1() { + + local KUBE_PS1 + local KUBE_PS1_RESET_COLOR="${_KUBE_PS1_OPEN_ESC}${_KUBE_PS1_DEFAULT_FG}${_KUBE_PS1_CLOSE_ESC}" ++ local ctx_color="${KUBE_PS1_CTX_COLOR-red}" ++ local ns_color="${KUBE_PS1_NS_COLOR-cyan}" + + # Background Color + [[ -n "${KUBE_PS1_BG_COLOR}" ]] && KUBE_PS1+="$(_kube_ps1_color_bg "${KUBE_PS1_BG_COLOR}")" +@@ -432,22 +434,29 @@ kube_ps1() { + + # Context + if [[ "${KUBE_PS1_CONTEXT_ENABLE}" == true ]]; then +- local ctx_color="${KUBE_PS1_CTX_COLOR:-red}" +- + # Allow custom function to override color based on context + if [[ -n "${KUBE_PS1_CTX_COLOR_FUNCTION}" ]]; then + ctx_color="$("${KUBE_PS1_CTX_COLOR_FUNCTION}" "${KUBE_PS1_CONTEXT}")" + fi + +- KUBE_PS1+="$(_kube_ps1_color_fg "${ctx_color}")${KUBE_PS1_CONTEXT}${KUBE_PS1_RESET_COLOR}" ++ if [[ -n "${ctx_color}" ]]; then ++ KUBE_PS1+="$(_kube_ps1_color_fg "${ctx_color}")${KUBE_PS1_CONTEXT}${KUBE_PS1_RESET_COLOR}" ++ else ++ KUBE_PS1+="${KUBE_PS1_CONTEXT}" ++ fi + fi + + # Namespace + if [[ "${KUBE_PS1_NS_ENABLE}" == true ]]; then +- if [[ -n "${KUBE_PS1_DIVIDER}" ]] && [[ "${KUBE_PS1_CONTEXT_ENABLE}" == true ]]; then ++ if [[ -n "${KUBE_PS1_DIVIDER}" && "${KUBE_PS1_CONTEXT_ENABLE}" == true ]]; then + KUBE_PS1+="${KUBE_PS1_DIVIDER}" + fi +- KUBE_PS1+="$(_kube_ps1_color_fg "${KUBE_PS1_NS_COLOR:-cyan}")${KUBE_PS1_NAMESPACE}${KUBE_PS1_RESET_COLOR}" ++ ++ if [[ -n "${ns_color}" ]]; then ++ KUBE_PS1+="$(_kube_ps1_color_fg "${ns_color}")${KUBE_PS1_NAMESPACE}${KUBE_PS1_RESET_COLOR}" ++ else ++ KUBE_PS1+="${KUBE_PS1_NAMESPACE}" ++ fi + fi + + # Suffix +@@ -460,5 +469,5 @@ kube_ps1() { + # Close Background color if defined + [[ -n "${KUBE_PS1_BG_COLOR}" ]] && KUBE_PS1+="${_KUBE_PS1_OPEN_ESC}${_KUBE_PS1_DEFAULT_BG}${_KUBE_PS1_CLOSE_ESC}" + +- echo "${KUBE_PS1}" ++ printf '%s' "${KUBE_PS1}" + } diff --git a/tasks/ohmyzsh__ohmyzsh-14094/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14094/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..41dc12edcd02ef563a439532e17921e88eabe10d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14094/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace be8da5c77192eb3da3699ea7c5e47bdfaa5eea4e > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14094/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14094/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14094/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14104/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14104/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1dd9d2491b6fb673b10a050061d9bd153ace896a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14104/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 0ee67f042872d1dfab74270c31867771ca35aef4 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 0ee67f042872d1dfab74270c31867771ca35aef4 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 0ee67f042872d1dfab74270c31867771ca35aef4 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14104/instruction.md b/tasks/ohmyzsh__ohmyzsh-14104/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7c0d3946a62c272405d73d9e3e314ed6ccadb22f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14104/instruction.md @@ -0,0 +1,61 @@ +# Issue + +**Title:** fix(cli): re-resolve zsh at exec time to avoid a stale command hash + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +### Summary + +#13922 replaced a non-absolute `ZSH_ARGZERO` with `$commands[zsh]` and exec'd that path. `$commands` is backed by the command hash table, whose entries are not invalidated when their target is deleted, so reload can exec a dead path and fail with `no such file or directory` (exit 127); the pre-#13922 bare `exec zsh` re-searched `$PATH` and did not. . + +### Fix + +Both exec sites (`_omz::reload`, the post-update restart) now set the bare command name and let `exec` resolve it through `$PATH` itself, since zsh re-validates a dangling hash entry at exec time: + +```diff + # ZSH_ARGZERO is how zsh was invoked, not the path to it, so re-resolve +- # anything that is not absolute () +- [[ "${zsh#-}" != /* ]] && (( $+commands[zsh] )) && zsh="$commands[zsh]" ++ # anything that is not absolute via $PATH at exec time () ++ [[ "${zsh#-}" != /* ]] && (( $+commands[zsh] )) && zsh="zsh" +``` + +The same zsh is selected in every case #13922 covered (first zsh on `$PATH`); only the dead-path failure changes. The `$+commands[zsh]` guard stays so a value is only replaced when a zsh exists on `$PATH`. + +## Other comments: + +### Verification + +Verified on zsh 5.9 (Alpine container) with the exact code before/after, exec'ing real targets via `exec -a` to set each `ZSH_ARGZERO` form: + +| `ZSH_ARGZERO` (state) | before (merged) | after (this PR) | +|---|---|---| +| `zsh`, fresh hash | first `$PATH` zsh | same | +| `-zsh`, fresh hash | `exec -l` first `$PATH` zsh | same | +| `./bin/zsh` after a cwd change, fresh hash | first `$PATH` zsh | same | +| `/usr/bin/zsh`, `-/usr/bin/zsh` | untouched | untouched | +| `zsh`, no zsh on `$PATH` | `command not found` (value kept) | same | +| `./custom/zsh` still valid | first `$PATH` zsh (reviewed #13922 behavior) | same | +| `zsh` / `-zsh` / `./gone/zsh`, **stale hash** (cached path deleted) | `no such file or directory: `, **127** | next zsh on `$PATH`, exit 0 | + +Login end-to-end with a real zsh target: both versions start the new zsh with `LOGIN=on` (`ARGZERO=-zsh`). `zsh -n lib/cli.zsh` passes. + +AI disclosure: this change was prepared with AI coding agents, reviewed and revised line by line by me. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0ee67f042872`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14104/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14104/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0d92c6af3970472de2f9838c856a6150ad9675c1 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14104/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/lib/cli.zsh b/lib/cli.zsh +index 48fa8995..c713db5d 100644 +--- a/lib/cli.zsh ++++ b/lib/cli.zsh +@@ -739,8 +739,8 @@ function _omz::reload { + # Old zsh versions don't have ZSH_ARGZERO + local zsh="${ZSH_ARGZERO:-${functrace[-1]%:*}}" + # ZSH_ARGZERO is how zsh was invoked, not the path to it, so re-resolve +- # anything that is not absolute (see #13919) +- [[ "${zsh#-}" != /* ]] && (( $+commands[zsh] )) && zsh="$commands[zsh]" ++ # anything that is not absolute via $PATH at exec time (see #13919) ++ [[ "${zsh#-}" != /* ]] && (( $+commands[zsh] )) && zsh="zsh" + # Check whether to run a login shell + [[ "$zsh" = -* || -o login ]] && exec -l "${zsh#-}" || exec "$zsh" + } +@@ -923,8 +923,8 @@ function _omz::update { + # Old zsh versions don't have ZSH_ARGZERO + local zsh="${ZSH_ARGZERO:-${functrace[-1]%:*}}" + # ZSH_ARGZERO is how zsh was invoked, not the path to it, so re-resolve +- # anything that is not absolute (see #13919) +- [[ "${zsh#-}" != /* ]] && (( $+commands[zsh] )) && zsh="$commands[zsh]" ++ # anything that is not absolute via $PATH at exec time (see #13919) ++ [[ "${zsh#-}" != /* ]] && (( $+commands[zsh] )) && zsh="zsh" + # Check whether to run a login shell + [[ "$zsh" = -* || -o login ]] && exec -l "${zsh#-}" || exec "$zsh" + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14104/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14104/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14104/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14104/task.toml b/tasks/ohmyzsh__ohmyzsh-14104/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3b80b83bddeae3bd097da66cfef33683514ccf57 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14104/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14104" +description = "fix(cli): re-resolve zsh at exec time to avoid a stale command hash" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "0ee67f042872d1dfab74270c31867771ca35aef4" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14104" +source_access = "auto" +built_at = "2026-11-16T16:09:56.935076+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:00f76430aa4c85aece25cddff2eda2f3acbb5ab221b83262d4c1b742f37efdc2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-18T09:06:03Z" +diff_format = "unified" +context_files = [ + "lib/cli.zsh", +] +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.988382+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a5fdd0fcf3933b717f08e17fa457deb3e665e1207c97b70beaaa45b1ea503848" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14104/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14104/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14104/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14104/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14104/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7c0d3946a62c272405d73d9e3e314ed6ccadb22f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14104/tests/instruction.md @@ -0,0 +1,61 @@ +# Issue + +**Title:** fix(cli): re-resolve zsh at exec time to avoid a stale command hash + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +### Summary + +#13922 replaced a non-absolute `ZSH_ARGZERO` with `$commands[zsh]` and exec'd that path. `$commands` is backed by the command hash table, whose entries are not invalidated when their target is deleted, so reload can exec a dead path and fail with `no such file or directory` (exit 127); the pre-#13922 bare `exec zsh` re-searched `$PATH` and did not. . + +### Fix + +Both exec sites (`_omz::reload`, the post-update restart) now set the bare command name and let `exec` resolve it through `$PATH` itself, since zsh re-validates a dangling hash entry at exec time: + +```diff + # ZSH_ARGZERO is how zsh was invoked, not the path to it, so re-resolve +- # anything that is not absolute () +- [[ "${zsh#-}" != /* ]] && (( $+commands[zsh] )) && zsh="$commands[zsh]" ++ # anything that is not absolute via $PATH at exec time () ++ [[ "${zsh#-}" != /* ]] && (( $+commands[zsh] )) && zsh="zsh" +``` + +The same zsh is selected in every case #13922 covered (first zsh on `$PATH`); only the dead-path failure changes. The `$+commands[zsh]` guard stays so a value is only replaced when a zsh exists on `$PATH`. + +## Other comments: + +### Verification + +Verified on zsh 5.9 (Alpine container) with the exact code before/after, exec'ing real targets via `exec -a` to set each `ZSH_ARGZERO` form: + +| `ZSH_ARGZERO` (state) | before (merged) | after (this PR) | +|---|---|---| +| `zsh`, fresh hash | first `$PATH` zsh | same | +| `-zsh`, fresh hash | `exec -l` first `$PATH` zsh | same | +| `./bin/zsh` after a cwd change, fresh hash | first `$PATH` zsh | same | +| `/usr/bin/zsh`, `-/usr/bin/zsh` | untouched | untouched | +| `zsh`, no zsh on `$PATH` | `command not found` (value kept) | same | +| `./custom/zsh` still valid | first `$PATH` zsh (reviewed #13922 behavior) | same | +| `zsh` / `-zsh` / `./gone/zsh`, **stale hash** (cached path deleted) | `no such file or directory: `, **127** | next zsh on `$PATH`, exit 0 | + +Login end-to-end with a real zsh target: both versions start the new zsh with `LOGIN=on` (`ARGZERO=-zsh`). `zsh -n lib/cli.zsh` passes. + +AI disclosure: this change was prepared with AI coding agents, reviewed and revised line by line by me. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0ee67f042872`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14104/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14104/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0d92c6af3970472de2f9838c856a6150ad9675c1 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14104/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/lib/cli.zsh b/lib/cli.zsh +index 48fa8995..c713db5d 100644 +--- a/lib/cli.zsh ++++ b/lib/cli.zsh +@@ -739,8 +739,8 @@ function _omz::reload { + # Old zsh versions don't have ZSH_ARGZERO + local zsh="${ZSH_ARGZERO:-${functrace[-1]%:*}}" + # ZSH_ARGZERO is how zsh was invoked, not the path to it, so re-resolve +- # anything that is not absolute (see #13919) +- [[ "${zsh#-}" != /* ]] && (( $+commands[zsh] )) && zsh="$commands[zsh]" ++ # anything that is not absolute via $PATH at exec time (see #13919) ++ [[ "${zsh#-}" != /* ]] && (( $+commands[zsh] )) && zsh="zsh" + # Check whether to run a login shell + [[ "$zsh" = -* || -o login ]] && exec -l "${zsh#-}" || exec "$zsh" + } +@@ -923,8 +923,8 @@ function _omz::update { + # Old zsh versions don't have ZSH_ARGZERO + local zsh="${ZSH_ARGZERO:-${functrace[-1]%:*}}" + # ZSH_ARGZERO is how zsh was invoked, not the path to it, so re-resolve +- # anything that is not absolute (see #13919) +- [[ "${zsh#-}" != /* ]] && (( $+commands[zsh] )) && zsh="$commands[zsh]" ++ # anything that is not absolute via $PATH at exec time (see #13919) ++ [[ "${zsh#-}" != /* ]] && (( $+commands[zsh] )) && zsh="zsh" + # Check whether to run a login shell + [[ "$zsh" = -* || -o login ]] && exec -l "${zsh#-}" || exec "$zsh" + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14104/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14104/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..87ead2db88d163fb9676e56bd33c47ebcbb1db73 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14104/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 0ee67f042872d1dfab74270c31867771ca35aef4 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14104/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14104/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14104/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14108/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14108/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1dd9d2491b6fb673b10a050061d9bd153ace896a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14108/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 0ee67f042872d1dfab74270c31867771ca35aef4 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 0ee67f042872d1dfab74270c31867771ca35aef4 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 0ee67f042872d1dfab74270c31867771ca35aef4 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14108/instruction.md b/tasks/ohmyzsh__ohmyzsh-14108/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..61d7f7d9277c1783961f3946e3929cdf18e0ce8c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14108/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** feat(eza): Add options for octal, inodes, and links for eza plugin + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +Added options that allow the user to toggle octal bites, inodes, and links on long form of eza + +## Other comments: + +... + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0ee67f042872`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14108/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14108/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d6c09821282950a666fe99b8c631b353da5e3ccd --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14108/solution/patch.diff @@ -0,0 +1,61 @@ +diff --git a/plugins/eza/README.md b/plugins/eza/README.md +index 5c2f590e..685bd726 100644 +--- a/plugins/eza/README.md ++++ b/plugins/eza/README.md +@@ -45,6 +45,36 @@ If `yes`, always add `-h` flag to add a header row for each column. + + Default: `no` + ++### `links` ++ ++```zsh ++zstyle ':omz:plugins:eza' 'links' yes|no ++``` ++ ++If `yes`, always add `-H` flag to show hard links for each file. ++ ++Default: `no` ++ ++### `octal` ++ ++```zsh ++zstyle ':omz:plugins:eza' 'octal' yes|no ++``` ++ ++If `yes`, always add `-o` flag to show file permissions as octal numbers. ++ ++Default: `no` ++ ++### `inodes` ++ ++```zsh ++zstyle ':omz:plugins:eza' 'inodes' yes|no ++``` ++ ++If `yes`, always add `-i` flag to show the inode for each file. ++ ++Default: `no` ++ + ### `show-group` + + ```zsh +diff --git a/plugins/eza/eza.plugin.zsh b/plugins/eza/eza.plugin.zsh +index 8809d8f3..35ea74e5 100644 +--- a/plugins/eza/eza.plugin.zsh ++++ b/plugins/eza/eza.plugin.zsh +@@ -21,6 +21,15 @@ function _configure_eza() { + if zstyle -t ':omz:plugins:eza' 'header'; then + _EZA_HEAD+=("h") + fi ++ if zstyle -t ':omz:plugins:eza' 'links'; then ++ _EZA_HEAD+=("H") ++ fi ++ if zstyle -t ':omz:plugins:eza' 'octal'; then ++ _EZA_HEAD+=("o") ++ fi ++ if zstyle -t ':omz:plugins:eza' 'inodes'; then ++ _EZA_HEAD+=("i") ++ fi + zstyle -s ':omz:plugins:eza' 'size-prefix' _val + case "${_val:l}" in + binary) diff --git a/tasks/ohmyzsh__ohmyzsh-14108/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14108/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14108/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14108/task.toml b/tasks/ohmyzsh__ohmyzsh-14108/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5b6591f91a9c4f31e11337fb1afb4e43870f660a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14108/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14108" +description = "feat(eza): Add options for octal, inodes, and links for eza plugin" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "0ee67f042872d1dfab74270c31867771ca35aef4" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14108" +source_access = "auto" +built_at = "2026-11-16T16:09:56.915921+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:efabb911328790f4b0e20229d8ee80c51fd2ee09e37644e42785a6a7b0574b5d" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-23T00:24:49Z" +diff_format = "unified" +context_files = [ + "plugins/eza/README.md", + "plugins/eza/eza.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 39 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.988862+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a5fdd0fcf3933b717f08e17fa457deb3e665e1207c97b70beaaa45b1ea503848" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14108/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14108/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14108/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14108/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14108/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..61d7f7d9277c1783961f3946e3929cdf18e0ce8c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14108/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** feat(eza): Add options for octal, inodes, and links for eza plugin + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +Added options that allow the user to toggle octal bites, inodes, and links on long form of eza + +## Other comments: + +... + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0ee67f042872`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14108/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14108/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d6c09821282950a666fe99b8c631b353da5e3ccd --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14108/tests/oracle.patch @@ -0,0 +1,61 @@ +diff --git a/plugins/eza/README.md b/plugins/eza/README.md +index 5c2f590e..685bd726 100644 +--- a/plugins/eza/README.md ++++ b/plugins/eza/README.md +@@ -45,6 +45,36 @@ If `yes`, always add `-h` flag to add a header row for each column. + + Default: `no` + ++### `links` ++ ++```zsh ++zstyle ':omz:plugins:eza' 'links' yes|no ++``` ++ ++If `yes`, always add `-H` flag to show hard links for each file. ++ ++Default: `no` ++ ++### `octal` ++ ++```zsh ++zstyle ':omz:plugins:eza' 'octal' yes|no ++``` ++ ++If `yes`, always add `-o` flag to show file permissions as octal numbers. ++ ++Default: `no` ++ ++### `inodes` ++ ++```zsh ++zstyle ':omz:plugins:eza' 'inodes' yes|no ++``` ++ ++If `yes`, always add `-i` flag to show the inode for each file. ++ ++Default: `no` ++ + ### `show-group` + + ```zsh +diff --git a/plugins/eza/eza.plugin.zsh b/plugins/eza/eza.plugin.zsh +index 8809d8f3..35ea74e5 100644 +--- a/plugins/eza/eza.plugin.zsh ++++ b/plugins/eza/eza.plugin.zsh +@@ -21,6 +21,15 @@ function _configure_eza() { + if zstyle -t ':omz:plugins:eza' 'header'; then + _EZA_HEAD+=("h") + fi ++ if zstyle -t ':omz:plugins:eza' 'links'; then ++ _EZA_HEAD+=("H") ++ fi ++ if zstyle -t ':omz:plugins:eza' 'octal'; then ++ _EZA_HEAD+=("o") ++ fi ++ if zstyle -t ':omz:plugins:eza' 'inodes'; then ++ _EZA_HEAD+=("i") ++ fi + zstyle -s ':omz:plugins:eza' 'size-prefix' _val + case "${_val:l}" in + binary) diff --git a/tasks/ohmyzsh__ohmyzsh-14108/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14108/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..87ead2db88d163fb9676e56bd33c47ebcbb1db73 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14108/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 0ee67f042872d1dfab74270c31867771ca35aef4 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14108/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14108/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14108/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14109/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14109/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f4b4c1f93850e29c1763e87e6b0c348d33986ff7 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14109/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e7852049a58ea5379dd8d88e97be89579b46a55b 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e7852049a58ea5379dd8d88e97be89579b46a55b \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e7852049a58ea5379dd8d88e97be89579b46a55b \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14109/instruction.md b/tasks/ohmyzsh__ohmyzsh-14109/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..361b9dfcf4339920fd499f92a6320ee287ff9448 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14109/instruction.md @@ -0,0 +1,42 @@ +# Issue + +**Title:** fix(tmux): sanitize `tds` session names for tmux target syntax + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +`tds` names its session after the current directory, but `tmux new -A -s NAME` looks NAME up as a **target** when the session already exists. tmux's target syntax treats `.` and `:` as separators and a leading `$`, `@` or `%` as an id. So in a directory like `example.com`, `v1.2.3` or `.hidden` the first `tds` creates the session and every later one fails: + +``` +$ cd example.com && tds # works, creates example.com-e71c75 +$ tds # can't find pane: com-e71c75 +``` + +This replaces those characters with `_` before building the name (`example.com` → `example_com-e71c75`). The hash suffix is untouched, so uniqueness per directory is preserved. + +Tested on tmux 3.7c with `.`, `:`, leading `$`/`@`/`%`, spaces, unicode and plain names: all now create and re-find correctly. + +## Other comments: + +Only directories containing the affected characters get a different session name than before, and those could never be reattached anyway. The `ZSH_TMUX_AUTONAME_SESSION` path in `_zsh_tmux_plugin_run` has the same class of issue (`attach -t "$session_name"`); I left it alone to keep this focused, happy to extend if wanted. + +AI disclosure: Claude Code helped investigate the tmux target-parsing behaviour and draft this description. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e7852049a58e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14109/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14109/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..986007b1f65942a048b056d5c6f17a955289005e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14109/solution/patch.diff @@ -0,0 +1,16 @@ +diff --git a/plugins/tmux/tmux.plugin.zsh b/plugins/tmux/tmux.plugin.zsh +index 9759d216..8b200757 100644 +--- a/plugins/tmux/tmux.plugin.zsh ++++ b/plugins/tmux/tmux.plugin.zsh +@@ -178,6 +178,11 @@ alias tmux=_zsh_tmux_plugin_run + function _tmux_directory_session() { + # current directory without leading path + local dir=${PWD##*/} ++ # tmux target syntax treats '.' and ':' as separators, a leading '$', '@' or '%' ++ # as an id and a leading '=' as an exact-match prefix, so a session named after ++ # such a directory can't be found on reattach ++ dir=${dir//[.:]/_} ++ dir=${dir/#[\$@%=]/_} + # md5 hash for the full working directory path + local md5=$(printf '%s' "$PWD" | md5sum | cut -d ' ' -f 1) + # human friendly unique session name for this directory diff --git a/tasks/ohmyzsh__ohmyzsh-14109/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14109/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14109/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14109/task.toml b/tasks/ohmyzsh__ohmyzsh-14109/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bc9710cea671364fd4cb371b671610f8bb9de856 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14109/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14109" +description = "fix(tmux): sanitize `tds` session names for tmux target syntax" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "e7852049a58ea5379dd8d88e97be89579b46a55b" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14109" +source_access = "auto" +built_at = "2026-11-16T16:09:56.929242+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:694e8fd1229663b80e31908a0b66f65c4fca24e3c3f321cd058ace9c1a3824d7" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-19T06:20:55Z" +diff_format = "unified" +context_files = [ + "plugins/tmux/tmux.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.989370+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3e3c8075459c5b1e0c7e061140d1684ca30a5fe7e362a72cab73d9e628aa7f17" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14109/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14109/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14109/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14109/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14109/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..361b9dfcf4339920fd499f92a6320ee287ff9448 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14109/tests/instruction.md @@ -0,0 +1,42 @@ +# Issue + +**Title:** fix(tmux): sanitize `tds` session names for tmux target syntax + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +`tds` names its session after the current directory, but `tmux new -A -s NAME` looks NAME up as a **target** when the session already exists. tmux's target syntax treats `.` and `:` as separators and a leading `$`, `@` or `%` as an id. So in a directory like `example.com`, `v1.2.3` or `.hidden` the first `tds` creates the session and every later one fails: + +``` +$ cd example.com && tds # works, creates example.com-e71c75 +$ tds # can't find pane: com-e71c75 +``` + +This replaces those characters with `_` before building the name (`example.com` → `example_com-e71c75`). The hash suffix is untouched, so uniqueness per directory is preserved. + +Tested on tmux 3.7c with `.`, `:`, leading `$`/`@`/`%`, spaces, unicode and plain names: all now create and re-find correctly. + +## Other comments: + +Only directories containing the affected characters get a different session name than before, and those could never be reattached anyway. The `ZSH_TMUX_AUTONAME_SESSION` path in `_zsh_tmux_plugin_run` has the same class of issue (`attach -t "$session_name"`); I left it alone to keep this focused, happy to extend if wanted. + +AI disclosure: Claude Code helped investigate the tmux target-parsing behaviour and draft this description. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e7852049a58e`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14109/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14109/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..986007b1f65942a048b056d5c6f17a955289005e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14109/tests/oracle.patch @@ -0,0 +1,16 @@ +diff --git a/plugins/tmux/tmux.plugin.zsh b/plugins/tmux/tmux.plugin.zsh +index 9759d216..8b200757 100644 +--- a/plugins/tmux/tmux.plugin.zsh ++++ b/plugins/tmux/tmux.plugin.zsh +@@ -178,6 +178,11 @@ alias tmux=_zsh_tmux_plugin_run + function _tmux_directory_session() { + # current directory without leading path + local dir=${PWD##*/} ++ # tmux target syntax treats '.' and ':' as separators, a leading '$', '@' or '%' ++ # as an id and a leading '=' as an exact-match prefix, so a session named after ++ # such a directory can't be found on reattach ++ dir=${dir//[.:]/_} ++ dir=${dir/#[\$@%=]/_} + # md5 hash for the full working directory path + local md5=$(printf '%s' "$PWD" | md5sum | cut -d ' ' -f 1) + # human friendly unique session name for this directory diff --git a/tasks/ohmyzsh__ohmyzsh-14109/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14109/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..6fe9ea2e62b40f8424f4cf92e2a65ded005f91ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14109/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace e7852049a58ea5379dd8d88e97be89579b46a55b > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14109/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14109/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14109/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14111/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14111/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa61e38537a2ed348286e09e96d6d35ad687b28b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14111/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 157eb033f2a527021aac18c1f5850bbe3e3d223c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 157eb033f2a527021aac18c1f5850bbe3e3d223c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 157eb033f2a527021aac18c1f5850bbe3e3d223c \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14111/instruction.md b/tasks/ohmyzsh__ohmyzsh-14111/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7e4aeddce1964796f55a24608a89527c4a84cce6 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14111/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** feat(hermes): add hermes plugin + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Added `hermes` plugin. + +## Other comments: + +I only used AI to quickly extract the names and descriptions of the completions. All other wording and formatting are from my own hands. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `157eb033f2a5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14111/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14111/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..aeee1f3686d5b17d2a21e611cf9269e86921cd7e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14111/solution/patch.diff @@ -0,0 +1,67 @@ +diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS +index 17e8b43c..61724104 100644 +--- a/.github/CODEOWNERS ++++ b/.github/CODEOWNERS +@@ -5,6 +5,7 @@ plugins/eza/ @pepoluan + plugins/genpass/ @atoponce + plugins/git-lfs/ @hellovietduc + plugins/gitfast/ @felipec ++plugins/hermes/ @Uhm-why + plugins/kube-ps1/ @mcornella + plugins/kubectl/ @mcornella + plugins/kubectx/ @mcornella +diff --git a/plugins/hermes/README.md b/plugins/hermes/README.md +new file mode 100644 +index 00000000..96d40299 +--- /dev/null ++++ b/plugins/hermes/README.md +@@ -0,0 +1,28 @@ ++# hermes plugin ++ ++This plugin adds completions for the Hermes AI agent. ++ ++To use it, add `hermes` to the plugin array in your zshrc file: ++ ++```zsh ++plugins=(... hermes) ++``` ++ ++## Usage ++ ++```zsh ++hermes ++``` ++ ++## Common Workflows ++ ++```zsh ++# First time setup/updating overall config ++hermes setup ++ ++# Starting the tui chat ++hermes ++ ++# Changing default model ++hermes model ++``` +diff --git a/plugins/hermes/hermes.plugin.zsh b/plugins/hermes/hermes.plugin.zsh +new file mode 100644 +index 00000000..437c1211 +--- /dev/null ++++ b/plugins/hermes/hermes.plugin.zsh +@@ -0,0 +1,15 @@ ++if (( ! $+commands[hermes] )); then ++ return ++fi ++ ++if [[ ! -f "$ZSH_CACHE_DIR/completions/_hermes" ]]; then ++ typeset -g -A _comps ++ autoload -Uz _hermes ++ _comps[hermes]=_hermes ++fi ++ ++zmodload -F zsh/files b:zf_mv ++() { ++ local TMPPREFIX="$ZSH_CACHE_DIR/completions/_hermes" ++ zf_mv -f -- =( hermes completion zsh < /dev/null 2> /dev/null ) "$TMPPREFIX" ++} &| diff --git a/tasks/ohmyzsh__ohmyzsh-14111/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14111/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14111/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14111/task.toml b/tasks/ohmyzsh__ohmyzsh-14111/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..82e760427786365d7eb8f9b5b36d99ef7e7dbe9e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14111/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14111" +description = "feat(hermes): add hermes plugin" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "157eb033f2a527021aac18c1f5850bbe3e3d223c" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14111" +source_access = "auto" +built_at = "2026-11-16T16:09:56.917476+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e648bd36ffa583b590e19ed4838e0e0daa6ae8e905e74a6158d4334823da58c3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-22T09:32:53Z" +diff_format = "unified" +context_files = [ + ".github/CODEOWNERS", + "plugins/hermes/README.md", + "plugins/hermes/hermes.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 44 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.989836+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a25563f37eaed12ce1049342aed791624ca7f296e8284f8e3355f505d3c6bb28" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14111/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14111/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14111/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14111/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14111/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7e4aeddce1964796f55a24608a89527c4a84cce6 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14111/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** feat(hermes): add hermes plugin + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Added `hermes` plugin. + +## Other comments: + +I only used AI to quickly extract the names and descriptions of the completions. All other wording and formatting are from my own hands. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `157eb033f2a5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14111/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14111/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..aeee1f3686d5b17d2a21e611cf9269e86921cd7e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14111/tests/oracle.patch @@ -0,0 +1,67 @@ +diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS +index 17e8b43c..61724104 100644 +--- a/.github/CODEOWNERS ++++ b/.github/CODEOWNERS +@@ -5,6 +5,7 @@ plugins/eza/ @pepoluan + plugins/genpass/ @atoponce + plugins/git-lfs/ @hellovietduc + plugins/gitfast/ @felipec ++plugins/hermes/ @Uhm-why + plugins/kube-ps1/ @mcornella + plugins/kubectl/ @mcornella + plugins/kubectx/ @mcornella +diff --git a/plugins/hermes/README.md b/plugins/hermes/README.md +new file mode 100644 +index 00000000..96d40299 +--- /dev/null ++++ b/plugins/hermes/README.md +@@ -0,0 +1,28 @@ ++# hermes plugin ++ ++This plugin adds completions for the Hermes AI agent. ++ ++To use it, add `hermes` to the plugin array in your zshrc file: ++ ++```zsh ++plugins=(... hermes) ++``` ++ ++## Usage ++ ++```zsh ++hermes ++``` ++ ++## Common Workflows ++ ++```zsh ++# First time setup/updating overall config ++hermes setup ++ ++# Starting the tui chat ++hermes ++ ++# Changing default model ++hermes model ++``` +diff --git a/plugins/hermes/hermes.plugin.zsh b/plugins/hermes/hermes.plugin.zsh +new file mode 100644 +index 00000000..437c1211 +--- /dev/null ++++ b/plugins/hermes/hermes.plugin.zsh +@@ -0,0 +1,15 @@ ++if (( ! $+commands[hermes] )); then ++ return ++fi ++ ++if [[ ! -f "$ZSH_CACHE_DIR/completions/_hermes" ]]; then ++ typeset -g -A _comps ++ autoload -Uz _hermes ++ _comps[hermes]=_hermes ++fi ++ ++zmodload -F zsh/files b:zf_mv ++() { ++ local TMPPREFIX="$ZSH_CACHE_DIR/completions/_hermes" ++ zf_mv -f -- =( hermes completion zsh < /dev/null 2> /dev/null ) "$TMPPREFIX" ++} &| diff --git a/tasks/ohmyzsh__ohmyzsh-14111/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14111/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8161a484144aaa6c8beb5a731dfcc1129a9d9126 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14111/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 157eb033f2a527021aac18c1f5850bbe3e3d223c > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14111/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14111/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14111/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14113/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14113/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa61e38537a2ed348286e09e96d6d35ad687b28b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14113/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 157eb033f2a527021aac18c1f5850bbe3e3d223c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 157eb033f2a527021aac18c1f5850bbe3e3d223c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 157eb033f2a527021aac18c1f5850bbe3e3d223c \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14113/instruction.md b/tasks/ohmyzsh__ohmyzsh-14113/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e71fc71a7d14217ac0f6d24ae899fb33009048e8 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14113/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** feat(glab): add GitLab CLI completions + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +This adds GitLab CLI (glab) completion support, following the same cached-completion approach used by the existing [gh plugin](https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/gh). The code intentionally follows the existing gh plugin implementation, only adapting the completion command for glab. + +## Other comments: + +This PR supersedes the abandoned #13307 with a deliberately minimal scope and addresses the still-open #13054. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `157eb033f2a5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14113/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14113/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4c963f7906ee2a4bed68a3efcd958cb0e792e78a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14113/solution/patch.diff @@ -0,0 +1,48 @@ +diff --git a/plugins/glab/README.md b/plugins/glab/README.md +new file mode 100644 +index 00000000..01723f7c +--- /dev/null ++++ b/plugins/glab/README.md +@@ -0,0 +1,18 @@ ++# GitLab CLI plugin ++ ++This plugin adds completion for the [GitLab CLI](https://docs.gitlab.com/cli/). ++ ++To use it, add `glab` to the plugins array in your zshrc file: ++ ++```zsh ++plugins=(... glab) ++``` ++ ++This plugin does not add any aliases. ++ ++## Cache ++ ++This plugin caches the completion script at `$ZSH_CACHE_DIR/completions/_glab`. ++ ++The cache is regenerated in the background whenever the plugin is loaded, which ++usually happens when you start a new Zsh session. +diff --git a/plugins/glab/glab.plugin.zsh b/plugins/glab/glab.plugin.zsh +new file mode 100644 +index 00000000..04ab9a27 +--- /dev/null ++++ b/plugins/glab/glab.plugin.zsh +@@ -0,0 +1,18 @@ ++# Autocompletion for the GitLab CLI (glab). ++if (( ! $+commands[glab] )); then ++ return ++fi ++ ++# If the completion file doesn't exist yet, we need to autoload it and ++# bind it to `glab`. Otherwise, compinit will have already done that. ++if [[ ! -f "$ZSH_CACHE_DIR/completions/_glab" ]]; then ++ typeset -g -A _comps ++ autoload -Uz _glab ++ _comps[glab]=_glab ++fi ++ ++zmodload -F zsh/files b:zf_mv ++() { ++ local TMPPREFIX="$ZSH_CACHE_DIR/completions/_glab" ++ zf_mv -f -- =( glab completion -s zsh ) "$TMPPREFIX" ++} &| diff --git a/tasks/ohmyzsh__ohmyzsh-14113/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14113/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14113/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14113/task.toml b/tasks/ohmyzsh__ohmyzsh-14113/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e84ee356a5fd02fda6dd2d3ec39d837f98ac24f5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14113/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14113" +description = "feat(glab): add GitLab CLI completions" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "157eb033f2a527021aac18c1f5850bbe3e3d223c" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14113" +source_access = "auto" +built_at = "2026-11-16T16:09:56.897072+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:01c9f77821f3ddc869425961e5ef9ca54b4aabf8cf0e90f60d0d5db09384524c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-23T00:23:22Z" +diff_format = "unified" +context_files = [ + "plugins/glab/README.md", + "plugins/glab/glab.plugin.zsh", +] +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.990291+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a25563f37eaed12ce1049342aed791624ca7f296e8284f8e3355f505d3c6bb28" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14113/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14113/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14113/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14113/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14113/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e71fc71a7d14217ac0f6d24ae899fb33009048e8 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14113/tests/instruction.md @@ -0,0 +1,31 @@ +# Issue + +**Title:** feat(glab): add GitLab CLI completions + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +This adds GitLab CLI (glab) completion support, following the same cached-completion approach used by the existing [gh plugin](https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/gh). The code intentionally follows the existing gh plugin implementation, only adapting the completion command for glab. + +## Other comments: + +This PR supersedes the abandoned #13307 with a deliberately minimal scope and addresses the still-open #13054. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `157eb033f2a5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14113/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14113/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4c963f7906ee2a4bed68a3efcd958cb0e792e78a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14113/tests/oracle.patch @@ -0,0 +1,48 @@ +diff --git a/plugins/glab/README.md b/plugins/glab/README.md +new file mode 100644 +index 00000000..01723f7c +--- /dev/null ++++ b/plugins/glab/README.md +@@ -0,0 +1,18 @@ ++# GitLab CLI plugin ++ ++This plugin adds completion for the [GitLab CLI](https://docs.gitlab.com/cli/). ++ ++To use it, add `glab` to the plugins array in your zshrc file: ++ ++```zsh ++plugins=(... glab) ++``` ++ ++This plugin does not add any aliases. ++ ++## Cache ++ ++This plugin caches the completion script at `$ZSH_CACHE_DIR/completions/_glab`. ++ ++The cache is regenerated in the background whenever the plugin is loaded, which ++usually happens when you start a new Zsh session. +diff --git a/plugins/glab/glab.plugin.zsh b/plugins/glab/glab.plugin.zsh +new file mode 100644 +index 00000000..04ab9a27 +--- /dev/null ++++ b/plugins/glab/glab.plugin.zsh +@@ -0,0 +1,18 @@ ++# Autocompletion for the GitLab CLI (glab). ++if (( ! $+commands[glab] )); then ++ return ++fi ++ ++# If the completion file doesn't exist yet, we need to autoload it and ++# bind it to `glab`. Otherwise, compinit will have already done that. ++if [[ ! -f "$ZSH_CACHE_DIR/completions/_glab" ]]; then ++ typeset -g -A _comps ++ autoload -Uz _glab ++ _comps[glab]=_glab ++fi ++ ++zmodload -F zsh/files b:zf_mv ++() { ++ local TMPPREFIX="$ZSH_CACHE_DIR/completions/_glab" ++ zf_mv -f -- =( glab completion -s zsh ) "$TMPPREFIX" ++} &| diff --git a/tasks/ohmyzsh__ohmyzsh-14113/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14113/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8161a484144aaa6c8beb5a731dfcc1129a9d9126 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14113/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 157eb033f2a527021aac18c1f5850bbe3e3d223c > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14113/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14113/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14113/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14115/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14115/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa61e38537a2ed348286e09e96d6d35ad687b28b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14115/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 157eb033f2a527021aac18c1f5850bbe3e3d223c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 157eb033f2a527021aac18c1f5850bbe3e3d223c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 157eb033f2a527021aac18c1f5850bbe3e3d223c \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14115/instruction.md b/tasks/ohmyzsh__ohmyzsh-14115/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..09f0e94796eafd017060242bf05b2f4a3d91dee7 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14115/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** chore(history-substring-search): update to version a0bdb0d4 + +## Description + +## Description + +Update for **history-substring-search plugin**: update to version . +Check out the [list of changes](https://github.com/zsh-users/zsh-history-substring-search/compare/zsh-users:14c8d2e...zsh-users:a0bdb0d). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `157eb033f2a5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14115/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14115/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3e2ef698c337278fcb5796e4ec67af7e2fd4657a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14115/solution/patch.diff @@ -0,0 +1,59 @@ +diff --git a/.github/dependencies.yml b/.github/dependencies.yml +index 5bd06bb3..046fdcec 100644 +--- a/.github/dependencies.yml ++++ b/.github/dependencies.yml +@@ -19,7 +19,7 @@ dependencies: + plugins/history-substring-search: + repo: zsh-users/zsh-history-substring-search + branch: master +- version: 14c8d2e0ffaee98f2df9850b19944f32546fdea5 ++ version: a0bdb0d47dbaba31dba2db7af8c48a5d9c74049a + precopy: | + set -e + rm -f zsh-history-substring-search.plugin.zsh +diff --git a/plugins/history-substring-search/README.md b/plugins/history-substring-search/README.md +index 642339bd..2ac2e587 100644 +--- a/plugins/history-substring-search/README.md ++++ b/plugins/history-substring-search/README.md +@@ -20,7 +20,7 @@ Requirements + Install + ------------------------------------------------------------------------------ + +-Using the [Homebrew](https://brew.sh) package manager: ++Using the [Homebrew]( https://brew.sh ) package manager: + + brew install zsh-history-substring-search + echo 'source $(brew --prefix)/share/zsh-history-substring-search/zsh-history-substring-search.zsh' >> ~/.zshrc +@@ -51,7 +51,7 @@ Using [zplug](https://github.com/zplug/zplug): + + 1. Add this repo to `~/.zshrc`: + +- zplug "zsh-users/zsh-history-substring-search", as: plugin ++ zplug "zsh-users/zsh-history-substring-search", as:plugin + + Using [antigen](https://github.com/zsh-users/antigen): + +@@ -75,7 +75,7 @@ Using [Zinit](https://github.com/zdharma-continuum/zinit): + + 1. Use the `Oh-my-zsh` Zinit snippet in `~/.zshrc`: + +- zinit snippet OMZ::plugins/git/git.plugin.zsh` ++ zinit snippet OMZ::plugins/git/git.plugin.zsh + + 2. Load the plugin in `~/.zshrc`: + +diff --git a/plugins/history-substring-search/history-substring-search.zsh b/plugins/history-substring-search/history-substring-search.zsh +index 9f0e0b0d..2137b795 100644 +--- a/plugins/history-substring-search/history-substring-search.zsh ++++ b/plugins/history-substring-search/history-substring-search.zsh +@@ -295,8 +295,8 @@ _history-substring-search-begin() { + fi + + # +- # Escape and join query parts with wildcard character '*' as separator +- # `(j:CHAR:)` join array to string with CHAR as separator ++ # Escape and join query parts with wildcard character '*' as seperator ++ # `(j:CHAR:)` join array to string with CHAR as seperator + # + local search_pattern="${(j:*:)_history_substring_search_query_parts[@]//(#m)[\][()|\\*?#<>~^]/\\$MATCH}*" + diff --git a/tasks/ohmyzsh__ohmyzsh-14115/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14115/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14115/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14115/task.toml b/tasks/ohmyzsh__ohmyzsh-14115/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0c328afc7993f06068a80002b84c388fae3d73d5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14115/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14115" +description = "chore(history-substring-search): update to version a0bdb0d4" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "157eb033f2a527021aac18c1f5850bbe3e3d223c" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14115" +source_access = "auto" +built_at = "2026-11-16T16:09:56.927474+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c34abc719acc290981a25a2ff7fd8cee7df2f7035147e2cd3236801dac0673c3" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-20T08:06:19Z" +diff_format = "unified" +context_files = [ + ".github/dependencies.yml", + "plugins/history-substring-search/README.md", + "plugins/history-substring-search/history-substring-search.zsh", +] +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.990878+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a25563f37eaed12ce1049342aed791624ca7f296e8284f8e3355f505d3c6bb28" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14115/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14115/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14115/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14115/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14115/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..09f0e94796eafd017060242bf05b2f4a3d91dee7 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14115/tests/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** chore(history-substring-search): update to version a0bdb0d4 + +## Description + +## Description + +Update for **history-substring-search plugin**: update to version . +Check out the [list of changes](https://github.com/zsh-users/zsh-history-substring-search/compare/zsh-users:14c8d2e...zsh-users:a0bdb0d). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `157eb033f2a5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14115/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14115/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3e2ef698c337278fcb5796e4ec67af7e2fd4657a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14115/tests/oracle.patch @@ -0,0 +1,59 @@ +diff --git a/.github/dependencies.yml b/.github/dependencies.yml +index 5bd06bb3..046fdcec 100644 +--- a/.github/dependencies.yml ++++ b/.github/dependencies.yml +@@ -19,7 +19,7 @@ dependencies: + plugins/history-substring-search: + repo: zsh-users/zsh-history-substring-search + branch: master +- version: 14c8d2e0ffaee98f2df9850b19944f32546fdea5 ++ version: a0bdb0d47dbaba31dba2db7af8c48a5d9c74049a + precopy: | + set -e + rm -f zsh-history-substring-search.plugin.zsh +diff --git a/plugins/history-substring-search/README.md b/plugins/history-substring-search/README.md +index 642339bd..2ac2e587 100644 +--- a/plugins/history-substring-search/README.md ++++ b/plugins/history-substring-search/README.md +@@ -20,7 +20,7 @@ Requirements + Install + ------------------------------------------------------------------------------ + +-Using the [Homebrew](https://brew.sh) package manager: ++Using the [Homebrew]( https://brew.sh ) package manager: + + brew install zsh-history-substring-search + echo 'source $(brew --prefix)/share/zsh-history-substring-search/zsh-history-substring-search.zsh' >> ~/.zshrc +@@ -51,7 +51,7 @@ Using [zplug](https://github.com/zplug/zplug): + + 1. Add this repo to `~/.zshrc`: + +- zplug "zsh-users/zsh-history-substring-search", as: plugin ++ zplug "zsh-users/zsh-history-substring-search", as:plugin + + Using [antigen](https://github.com/zsh-users/antigen): + +@@ -75,7 +75,7 @@ Using [Zinit](https://github.com/zdharma-continuum/zinit): + + 1. Use the `Oh-my-zsh` Zinit snippet in `~/.zshrc`: + +- zinit snippet OMZ::plugins/git/git.plugin.zsh` ++ zinit snippet OMZ::plugins/git/git.plugin.zsh + + 2. Load the plugin in `~/.zshrc`: + +diff --git a/plugins/history-substring-search/history-substring-search.zsh b/plugins/history-substring-search/history-substring-search.zsh +index 9f0e0b0d..2137b795 100644 +--- a/plugins/history-substring-search/history-substring-search.zsh ++++ b/plugins/history-substring-search/history-substring-search.zsh +@@ -295,8 +295,8 @@ _history-substring-search-begin() { + fi + + # +- # Escape and join query parts with wildcard character '*' as separator +- # `(j:CHAR:)` join array to string with CHAR as separator ++ # Escape and join query parts with wildcard character '*' as seperator ++ # `(j:CHAR:)` join array to string with CHAR as seperator + # + local search_pattern="${(j:*:)_history_substring_search_query_parts[@]//(#m)[\][()|\\*?#<>~^]/\\$MATCH}*" + diff --git a/tasks/ohmyzsh__ohmyzsh-14115/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14115/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8161a484144aaa6c8beb5a731dfcc1129a9d9126 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14115/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 157eb033f2a527021aac18c1f5850bbe3e3d223c > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14115/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14115/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14115/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14118/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14118/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..96a5f82ae7ef6ccdab9310fadf03ce07a1a421ec --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14118/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 86ef6555e068663736a33376e4055aca9c1acc89 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 86ef6555e068663736a33376e4055aca9c1acc89 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 86ef6555e068663736a33376e4055aca9c1acc89 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14118/instruction.md b/tasks/ohmyzsh__ohmyzsh-14118/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..50967b34a0abcf36266d86a1e0e50756e633066e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14118/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** feat(systemadmin)!: match ports 80 and 443 in con80, req20 and http20 + +## Description + +`con80`, `req20`, and `http20` hard-coded port 80. Most web traffic is HTTPS now, so counting port 80 alone misses most of it. With no argument they now match 80 and 443 together. Passing one or more ports narrows them to those, for example `con80 443` or `req20 8080 8443`. + +**Breaking:** the default output of `con80` and `req20` now includes port 443. `con80 80` gives the old number. + +`http20` also moves `-c 1000` before the filter expression, since BSD getopt stops at the first non-option argument. + +Tested in `zsh -f` with stubbed `ss`, `netstat`, `tcpdump` and `sudo`, using the Linux column layouts the existing awk programs assume: default, single-port and multi-port forms give the expected counts and IP lists, and the anchors do not match 8443 or 4430. The three tcpdump filter expressions compile with the real tcpdump. I had no GNU awk to run the filter on, though it is plain POSIX syntax. macOS `netstat` prints ports as `addr.port`, so these helpers have never matched there; that is pre-existing and handled separately. + +Not touched here: the `netstat` fallback in `req20` and five other helpers never runs, because `ss | awk` exits with awk's status. That is pre-existing and fixed in #14119. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `86ef6555e068`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14118/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14118/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f4727bb329d15c6a98a66dfda29b75678f7e21a5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14118/solution/patch.diff @@ -0,0 +1,78 @@ +diff --git a/plugins/systemadmin/README.md b/plugins/systemadmin/README.md +index f8266d8d..6a4f4ad4 100644 +--- a/plugins/systemadmin/README.md ++++ b/plugins/systemadmin/README.md +@@ -33,10 +33,10 @@ plugins=(... systemadmin) + | killit | Kills any process that matches a regular expression passed to it | + | tree | List contents of directories in a tree-like format (if tree isn't installed) | + | sortcons | Sort connections by state | +-| con80 | View all 80 Port Connections | ++| con80 | View all connections on ports 80 and 443, or on the ports given as arguments (`con80 8080`) | + | sortconip | On the connected IP sorted by the number of connections | +-| req20 | List the top 20 requests on port 80 | +-| http20 | List the top 20 connections to port 80 based on tcpdump data | ++| req20 | List the top 20 requests on ports 80 and 443, or on the ports given as arguments (`req20 8080`) | ++| http20 | List the top 20 connections to ports 80 and 443 based on tcpdump data, or to the ports given as arguments | + | timewait20 | List the top 20 time_wait connections | + | syn20 | List the top 20 SYN connections | + | port_pro | Output all processes according to the port number | +diff --git a/plugins/systemadmin/systemadmin.plugin.zsh b/plugins/systemadmin/systemadmin.plugin.zsh +index 1d95a1ba..589659f7 100644 +--- a/plugins/systemadmin/systemadmin.plugin.zsh ++++ b/plugins/systemadmin/systemadmin.plugin.zsh +@@ -71,11 +71,24 @@ function sortcons() { + } | sort | uniq -c | sort -rn + } + +-# View all 80 Port Connections ++function _systemadmin_validate_ports() { ++ local port ++ for port in "$@"; do ++ if [[ $port != <0-65535> || ( $port == 0* && $port != 0 ) ]]; then ++ print -u2 "systemadmin: invalid port '$port' (expected 0 to 65535 without leading zeros)" ++ return 1 ++ fi ++ done ++} ++ ++# View all connections on the given ports (default 80 and 443) + function con80() { ++ local -a ports=("$@") ++ (( $# )) || ports=(80 443) ++ _systemadmin_validate_ports "${ports[@]}" || return + { + LANG= ss -nat || LANG= netstat -nat +- } | grep -E ":80[^0-9]" | wc -l ++ } | grep -E ":(${(j:|:)ports})([[:space:]]|$)" | wc -l + } + + # On the connected IP sorted by the number of connections +@@ -86,17 +99,23 @@ function sortconip() { + } | cut -d: -f1 | sort | uniq -c | sort -n + } + +-# top20 of Find the number of requests on 80 port ++# top20 of Find the number of requests on the given ports (default 80 and 443) + function req20() { ++ local -a ports=("$@") ++ (( $# )) || ports=(80 443) ++ _systemadmin_validate_ports "${ports[@]}" || return + { +- LANG= ss -tn | awk '$4 ~ /:80$/ {print $5}' \ +- || LANG= netstat -tn | awk '$4 ~ /:80$/ {print $5}' ++ LANG= ss -tn | awk -v ports="${(j:|:)ports}" '$4 ~ ":("ports")$" {print $5}' \ ++ || LANG= netstat -tn | awk -v ports="${(j:|:)ports}" '$4 ~ ":("ports")$" {print $5}' + } | awk -F: '{print $1}' | sort | uniq -c | sort -nr | head -n 20 + } + +-# top20 of Using tcpdump port 80 access to view ++# top20 of Using tcpdump to view access to the given ports (default 80 and 443) + function http20() { +- sudo tcpdump -i eth0 -tnn dst port 80 -c 1000 | awk -F"." '{print $1"."$2"."$3"."$4}' | sort | uniq -c | sort -nr | head -n 20 ++ local -a ports=("$@") ++ (( $# )) || ports=(80 443) ++ _systemadmin_validate_ports "${ports[@]}" || return ++ sudo tcpdump -i eth0 -tnn -c 1000 "dst port ${(j: or :)ports}" | awk -F"." '{print $1"."$2"."$3"."$4}' | sort | uniq -c | sort -nr | head -n 20 + } + + # top20 of Find time_wait connection diff --git a/tasks/ohmyzsh__ohmyzsh-14118/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14118/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14118/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14118/task.toml b/tasks/ohmyzsh__ohmyzsh-14118/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a67f13ceddb4a311a8ed99b09c9f0051aca4e2ba --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14118/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14118" +description = "feat(systemadmin)!: match ports 80 and 443 in con80, req20 and http20" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "86ef6555e068663736a33376e4055aca9c1acc89" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14118" +source_access = "auto" +built_at = "2026-11-16T16:09:56.923321+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e14174431a7db4938ec35712412a5f1f65fe446e54de516b075154c17619603b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-22T15:42:42Z" +diff_format = "unified" +context_files = [ + "plugins/systemadmin/README.md", + "plugins/systemadmin/systemadmin.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 39 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.991531+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:80d5618b02a2b85eb9b47b1f6d5535788c3f94f1cae74ec5c46082104db7dc3a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14118/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14118/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14118/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14118/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14118/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..50967b34a0abcf36266d86a1e0e50756e633066e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14118/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** feat(systemadmin)!: match ports 80 and 443 in con80, req20 and http20 + +## Description + +`con80`, `req20`, and `http20` hard-coded port 80. Most web traffic is HTTPS now, so counting port 80 alone misses most of it. With no argument they now match 80 and 443 together. Passing one or more ports narrows them to those, for example `con80 443` or `req20 8080 8443`. + +**Breaking:** the default output of `con80` and `req20` now includes port 443. `con80 80` gives the old number. + +`http20` also moves `-c 1000` before the filter expression, since BSD getopt stops at the first non-option argument. + +Tested in `zsh -f` with stubbed `ss`, `netstat`, `tcpdump` and `sudo`, using the Linux column layouts the existing awk programs assume: default, single-port and multi-port forms give the expected counts and IP lists, and the anchors do not match 8443 or 4430. The three tcpdump filter expressions compile with the real tcpdump. I had no GNU awk to run the filter on, though it is plain POSIX syntax. macOS `netstat` prints ports as `addr.port`, so these helpers have never matched there; that is pre-existing and handled separately. + +Not touched here: the `netstat` fallback in `req20` and five other helpers never runs, because `ss | awk` exits with awk's status. That is pre-existing and fixed in #14119. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `86ef6555e068`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14118/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14118/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f4727bb329d15c6a98a66dfda29b75678f7e21a5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14118/tests/oracle.patch @@ -0,0 +1,78 @@ +diff --git a/plugins/systemadmin/README.md b/plugins/systemadmin/README.md +index f8266d8d..6a4f4ad4 100644 +--- a/plugins/systemadmin/README.md ++++ b/plugins/systemadmin/README.md +@@ -33,10 +33,10 @@ plugins=(... systemadmin) + | killit | Kills any process that matches a regular expression passed to it | + | tree | List contents of directories in a tree-like format (if tree isn't installed) | + | sortcons | Sort connections by state | +-| con80 | View all 80 Port Connections | ++| con80 | View all connections on ports 80 and 443, or on the ports given as arguments (`con80 8080`) | + | sortconip | On the connected IP sorted by the number of connections | +-| req20 | List the top 20 requests on port 80 | +-| http20 | List the top 20 connections to port 80 based on tcpdump data | ++| req20 | List the top 20 requests on ports 80 and 443, or on the ports given as arguments (`req20 8080`) | ++| http20 | List the top 20 connections to ports 80 and 443 based on tcpdump data, or to the ports given as arguments | + | timewait20 | List the top 20 time_wait connections | + | syn20 | List the top 20 SYN connections | + | port_pro | Output all processes according to the port number | +diff --git a/plugins/systemadmin/systemadmin.plugin.zsh b/plugins/systemadmin/systemadmin.plugin.zsh +index 1d95a1ba..589659f7 100644 +--- a/plugins/systemadmin/systemadmin.plugin.zsh ++++ b/plugins/systemadmin/systemadmin.plugin.zsh +@@ -71,11 +71,24 @@ function sortcons() { + } | sort | uniq -c | sort -rn + } + +-# View all 80 Port Connections ++function _systemadmin_validate_ports() { ++ local port ++ for port in "$@"; do ++ if [[ $port != <0-65535> || ( $port == 0* && $port != 0 ) ]]; then ++ print -u2 "systemadmin: invalid port '$port' (expected 0 to 65535 without leading zeros)" ++ return 1 ++ fi ++ done ++} ++ ++# View all connections on the given ports (default 80 and 443) + function con80() { ++ local -a ports=("$@") ++ (( $# )) || ports=(80 443) ++ _systemadmin_validate_ports "${ports[@]}" || return + { + LANG= ss -nat || LANG= netstat -nat +- } | grep -E ":80[^0-9]" | wc -l ++ } | grep -E ":(${(j:|:)ports})([[:space:]]|$)" | wc -l + } + + # On the connected IP sorted by the number of connections +@@ -86,17 +99,23 @@ function sortconip() { + } | cut -d: -f1 | sort | uniq -c | sort -n + } + +-# top20 of Find the number of requests on 80 port ++# top20 of Find the number of requests on the given ports (default 80 and 443) + function req20() { ++ local -a ports=("$@") ++ (( $# )) || ports=(80 443) ++ _systemadmin_validate_ports "${ports[@]}" || return + { +- LANG= ss -tn | awk '$4 ~ /:80$/ {print $5}' \ +- || LANG= netstat -tn | awk '$4 ~ /:80$/ {print $5}' ++ LANG= ss -tn | awk -v ports="${(j:|:)ports}" '$4 ~ ":("ports")$" {print $5}' \ ++ || LANG= netstat -tn | awk -v ports="${(j:|:)ports}" '$4 ~ ":("ports")$" {print $5}' + } | awk -F: '{print $1}' | sort | uniq -c | sort -nr | head -n 20 + } + +-# top20 of Using tcpdump port 80 access to view ++# top20 of Using tcpdump to view access to the given ports (default 80 and 443) + function http20() { +- sudo tcpdump -i eth0 -tnn dst port 80 -c 1000 | awk -F"." '{print $1"."$2"."$3"."$4}' | sort | uniq -c | sort -nr | head -n 20 ++ local -a ports=("$@") ++ (( $# )) || ports=(80 443) ++ _systemadmin_validate_ports "${ports[@]}" || return ++ sudo tcpdump -i eth0 -tnn -c 1000 "dst port ${(j: or :)ports}" | awk -F"." '{print $1"."$2"."$3"."$4}' | sort | uniq -c | sort -nr | head -n 20 + } + + # top20 of Find time_wait connection diff --git a/tasks/ohmyzsh__ohmyzsh-14118/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14118/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c47bb33502e89712a9a9470ccd49fbe610d6bbbe --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14118/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 86ef6555e068663736a33376e4055aca9c1acc89 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14118/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14118/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14118/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14119/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14119/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4f44e032b2eac8d50a8ae1ca6e842e7cab43797f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14119/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 7d1b2a25ca33638739c1570f1692104da15e966e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 7d1b2a25ca33638739c1570f1692104da15e966e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 7d1b2a25ca33638739c1570f1692104da15e966e \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14119/instruction.md b/tasks/ohmyzsh__ohmyzsh-14119/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..351bf4014a5a63f9583b0e3ba83e3ab059d7859b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14119/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** fix(systemadmin): make the netstat fallback reachable + +## Description + +Six helpers were written as `ss ... | awk ... || netstat ... | awk ...`. A pipeline exits with its last command's status, so a missing `ss` still ended in `awk` exiting 0 and the `netstat` branch never ran. On Linux systems without iproute2, `sortcons`, `sortconip`, `req20`, `timewait20`, `syn20` and `port_pro` printed nothing. + +Each helper now picks `ss` or `netstat` by whether `ss` is installed. `con80` gets the same shape so the file has one idiom and stops printing "command not found: ss" on the way to `netstat`. Where both backends share the same columns, the awk program is written once. + +This does not make the helpers work on macOS. macOS `netstat` prints ports as `addr.port` rather than `addr:port`, and its `-ntu` and `-ntlp` flags mean different things, so these helpers have never matched anything there. That is pre-existing and out of scope here. + +Tested with a script that runs all seven helpers before and after, with and without an `ss` stub, using the Linux column layouts the existing awk programs assume. With `ss` present, every helper's output is identical to before. Without it, the six broken helpers now produce output and stderr is empty. Stacked on #14118, which touches `req20`. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7d1b2a25ca33`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14119/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14119/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b0ab17caf1f14e21fff47aa302c1a8edd66234aa --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14119/solution/patch.diff @@ -0,0 +1,105 @@ +diff --git a/plugins/systemadmin/systemadmin.plugin.zsh b/plugins/systemadmin/systemadmin.plugin.zsh +index 589659f7..50bfadc4 100644 +--- a/plugins/systemadmin/systemadmin.plugin.zsh ++++ b/plugins/systemadmin/systemadmin.plugin.zsh +@@ -65,10 +65,11 @@ fi + + # Sort connection state + function sortcons() { +- { +- LANG= ss -nat | awk 'NR > 1 {print $1}' \ +- || LANG= netstat -nat | awk 'NR > 2 {print $6}' +- } | sort | uniq -c | sort -rn ++ if (( $+commands[ss] )); then ++ LANG= ss -nat | awk 'NR > 1 {print $1}' ++ else ++ LANG= netstat -nat | awk 'NR > 2 {print $6}' ++ fi | sort | uniq -c | sort -rn + } + + function _systemadmin_validate_ports() { +@@ -86,17 +87,20 @@ function con80() { + local -a ports=("$@") + (( $# )) || ports=(80 443) + _systemadmin_validate_ports "${ports[@]}" || return +- { +- LANG= ss -nat || LANG= netstat -nat +- } | grep -E ":(${(j:|:)ports})([[:space:]]|$)" | wc -l ++ if (( $+commands[ss] )); then ++ LANG= ss -nat ++ else ++ LANG= netstat -nat ++ fi | grep -E ":(${(j:|:)ports})([[:space:]]|$)" | wc -l + } + + # On the connected IP sorted by the number of connections + function sortconip() { +- { +- LANG= ss -ntu | awk 'NR > 1 {print $6}' \ +- || LANG= netstat -ntu | awk 'NR > 2 {print $5}' +- } | cut -d: -f1 | sort | uniq -c | sort -n ++ if (( $+commands[ss] )); then ++ LANG= ss -ntu | awk 'NR > 1 {print $6}' ++ else ++ LANG= netstat -ntu | awk 'NR > 2 {print $5}' ++ fi | cut -d: -f1 | sort | uniq -c | sort -n + } + + # top20 of Find the number of requests on the given ports (default 80 and 443) +@@ -104,10 +108,12 @@ function req20() { + local -a ports=("$@") + (( $# )) || ports=(80 443) + _systemadmin_validate_ports "${ports[@]}" || return +- { +- LANG= ss -tn | awk -v ports="${(j:|:)ports}" '$4 ~ ":("ports")$" {print $5}' \ +- || LANG= netstat -tn | awk -v ports="${(j:|:)ports}" '$4 ~ ":("ports")$" {print $5}' +- } | awk -F: '{print $1}' | sort | uniq -c | sort -nr | head -n 20 ++ if (( $+commands[ss] )); then ++ LANG= ss -tn ++ else ++ LANG= netstat -tn ++ fi | awk -v ports="${(j:|:)ports}" '$4 ~ ":("ports")$" {print $5}' \ ++ | awk -F: '{print $1}' | sort | uniq -c | sort -nr | head -n 20 + } + + # top20 of Using tcpdump to view access to the given ports (default 80 and 443) +@@ -120,24 +126,29 @@ function http20() { + + # top20 of Find time_wait connection + function timewait20() { +- { +- LANG= ss -nat | awk 'NR > 1 && /TIME-WAIT/ {print $5}' \ +- || LANG= netstat -nat | awk 'NR > 2 && /TIME_WAIT/ {print $5}' +- } | sort | uniq -c | sort -rn | head -n 20 ++ if (( $+commands[ss] )); then ++ LANG= ss -nat ++ else ++ LANG= netstat -nat ++ fi | awk '/TIME[-_]WAIT/ {print $5}' | sort | uniq -c | sort -rn | head -n 20 + } + + # top20 of Find SYN connection + function syn20() { +- { +- LANG= ss -an | awk '/SYN/ {print $5}' \ +- || LANG= netstat -an | awk '/SYN/ {print $5}' +- } | awk -F: '{print $1}' | sort | uniq -c | sort -nr | head -n20 ++ if (( $+commands[ss] )); then ++ LANG= ss -an ++ else ++ LANG= netstat -an ++ fi | awk '/SYN/ {print $5}' | awk -F: '{print $1}' | sort | uniq -c | sort -nr | head -n20 + } + + # Printing process according to the port number + function port_pro() { +- LANG= ss -ntlp | awk "NR > 1 && /:${1:-}/ {print \$6}" | sed 's/.*pid=\([^,]*\).*/\1/' \ +- || LANG= netstat -ntlp | awk "NR > 2 && /:${1:-}/ {print \$7}" | cut -d/ -f1 ++ if (( $+commands[ss] )); then ++ LANG= ss -ntlp | awk "NR > 1 && /:${1:-}/ {print \$6}" | sed 's/.*pid=\([^,]*\).*/\1/' ++ else ++ LANG= netstat -ntlp | awk "NR > 2 && /:${1:-}/ {print \$7}" | cut -d/ -f1 ++ fi + } + + # top10 of gain access to the ip address diff --git a/tasks/ohmyzsh__ohmyzsh-14119/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14119/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14119/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14119/task.toml b/tasks/ohmyzsh__ohmyzsh-14119/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bbe4f932b3a4be6d86b096c025c633d52a5be524 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14119/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14119" +description = "fix(systemadmin): make the netstat fallback reachable" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "7d1b2a25ca33638739c1570f1692104da15e966e" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14119" +source_access = "auto" +built_at = "2026-11-16T16:09:56.921832+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:91dc1b9f6bfc9360c921e293692a4efb3f297b8309f97b1280c1892917bce5c5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-22T15:45:06Z" +diff_format = "unified" +context_files = [ + "plugins/systemadmin/systemadmin.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 61 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.992229+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:8c88b31d43b0300fc374af86d4175751bedddcc36ac24cf10f43231087454f4b" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14119/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14119/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14119/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14119/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14119/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..351bf4014a5a63f9583b0e3ba83e3ab059d7859b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14119/tests/instruction.md @@ -0,0 +1,19 @@ +# Issue + +**Title:** fix(systemadmin): make the netstat fallback reachable + +## Description + +Six helpers were written as `ss ... | awk ... || netstat ... | awk ...`. A pipeline exits with its last command's status, so a missing `ss` still ended in `awk` exiting 0 and the `netstat` branch never ran. On Linux systems without iproute2, `sortcons`, `sortconip`, `req20`, `timewait20`, `syn20` and `port_pro` printed nothing. + +Each helper now picks `ss` or `netstat` by whether `ss` is installed. `con80` gets the same shape so the file has one idiom and stops printing "command not found: ss" on the way to `netstat`. Where both backends share the same columns, the awk program is written once. + +This does not make the helpers work on macOS. macOS `netstat` prints ports as `addr.port` rather than `addr:port`, and its `-ntu` and `-ntlp` flags mean different things, so these helpers have never matched anything there. That is pre-existing and out of scope here. + +Tested with a script that runs all seven helpers before and after, with and without an `ss` stub, using the Linux column layouts the existing awk programs assume. With `ss` present, every helper's output is identical to before. Without it, the six broken helpers now produce output and stderr is empty. Stacked on #14118, which touches `req20`. + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `7d1b2a25ca33`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14119/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14119/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b0ab17caf1f14e21fff47aa302c1a8edd66234aa --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14119/tests/oracle.patch @@ -0,0 +1,105 @@ +diff --git a/plugins/systemadmin/systemadmin.plugin.zsh b/plugins/systemadmin/systemadmin.plugin.zsh +index 589659f7..50bfadc4 100644 +--- a/plugins/systemadmin/systemadmin.plugin.zsh ++++ b/plugins/systemadmin/systemadmin.plugin.zsh +@@ -65,10 +65,11 @@ fi + + # Sort connection state + function sortcons() { +- { +- LANG= ss -nat | awk 'NR > 1 {print $1}' \ +- || LANG= netstat -nat | awk 'NR > 2 {print $6}' +- } | sort | uniq -c | sort -rn ++ if (( $+commands[ss] )); then ++ LANG= ss -nat | awk 'NR > 1 {print $1}' ++ else ++ LANG= netstat -nat | awk 'NR > 2 {print $6}' ++ fi | sort | uniq -c | sort -rn + } + + function _systemadmin_validate_ports() { +@@ -86,17 +87,20 @@ function con80() { + local -a ports=("$@") + (( $# )) || ports=(80 443) + _systemadmin_validate_ports "${ports[@]}" || return +- { +- LANG= ss -nat || LANG= netstat -nat +- } | grep -E ":(${(j:|:)ports})([[:space:]]|$)" | wc -l ++ if (( $+commands[ss] )); then ++ LANG= ss -nat ++ else ++ LANG= netstat -nat ++ fi | grep -E ":(${(j:|:)ports})([[:space:]]|$)" | wc -l + } + + # On the connected IP sorted by the number of connections + function sortconip() { +- { +- LANG= ss -ntu | awk 'NR > 1 {print $6}' \ +- || LANG= netstat -ntu | awk 'NR > 2 {print $5}' +- } | cut -d: -f1 | sort | uniq -c | sort -n ++ if (( $+commands[ss] )); then ++ LANG= ss -ntu | awk 'NR > 1 {print $6}' ++ else ++ LANG= netstat -ntu | awk 'NR > 2 {print $5}' ++ fi | cut -d: -f1 | sort | uniq -c | sort -n + } + + # top20 of Find the number of requests on the given ports (default 80 and 443) +@@ -104,10 +108,12 @@ function req20() { + local -a ports=("$@") + (( $# )) || ports=(80 443) + _systemadmin_validate_ports "${ports[@]}" || return +- { +- LANG= ss -tn | awk -v ports="${(j:|:)ports}" '$4 ~ ":("ports")$" {print $5}' \ +- || LANG= netstat -tn | awk -v ports="${(j:|:)ports}" '$4 ~ ":("ports")$" {print $5}' +- } | awk -F: '{print $1}' | sort | uniq -c | sort -nr | head -n 20 ++ if (( $+commands[ss] )); then ++ LANG= ss -tn ++ else ++ LANG= netstat -tn ++ fi | awk -v ports="${(j:|:)ports}" '$4 ~ ":("ports")$" {print $5}' \ ++ | awk -F: '{print $1}' | sort | uniq -c | sort -nr | head -n 20 + } + + # top20 of Using tcpdump to view access to the given ports (default 80 and 443) +@@ -120,24 +126,29 @@ function http20() { + + # top20 of Find time_wait connection + function timewait20() { +- { +- LANG= ss -nat | awk 'NR > 1 && /TIME-WAIT/ {print $5}' \ +- || LANG= netstat -nat | awk 'NR > 2 && /TIME_WAIT/ {print $5}' +- } | sort | uniq -c | sort -rn | head -n 20 ++ if (( $+commands[ss] )); then ++ LANG= ss -nat ++ else ++ LANG= netstat -nat ++ fi | awk '/TIME[-_]WAIT/ {print $5}' | sort | uniq -c | sort -rn | head -n 20 + } + + # top20 of Find SYN connection + function syn20() { +- { +- LANG= ss -an | awk '/SYN/ {print $5}' \ +- || LANG= netstat -an | awk '/SYN/ {print $5}' +- } | awk -F: '{print $1}' | sort | uniq -c | sort -nr | head -n20 ++ if (( $+commands[ss] )); then ++ LANG= ss -an ++ else ++ LANG= netstat -an ++ fi | awk '/SYN/ {print $5}' | awk -F: '{print $1}' | sort | uniq -c | sort -nr | head -n20 + } + + # Printing process according to the port number + function port_pro() { +- LANG= ss -ntlp | awk "NR > 1 && /:${1:-}/ {print \$6}" | sed 's/.*pid=\([^,]*\).*/\1/' \ +- || LANG= netstat -ntlp | awk "NR > 2 && /:${1:-}/ {print \$7}" | cut -d/ -f1 ++ if (( $+commands[ss] )); then ++ LANG= ss -ntlp | awk "NR > 1 && /:${1:-}/ {print \$6}" | sed 's/.*pid=\([^,]*\).*/\1/' ++ else ++ LANG= netstat -ntlp | awk "NR > 2 && /:${1:-}/ {print \$7}" | cut -d/ -f1 ++ fi + } + + # top10 of gain access to the ip address diff --git a/tasks/ohmyzsh__ohmyzsh-14119/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14119/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..08f22d8d0f3e36546f874af80db13dbdd732b6c4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14119/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 7d1b2a25ca33638739c1570f1692104da15e966e > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14119/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14119/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14119/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14120/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14120/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..83faf031610d0b3ee2d78157d94db1e0bd75a823 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14120/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin f809d46c10c59b3824c9be6c7ccb46db690cd441 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard f809d46c10c59b3824c9be6c7ccb46db690cd441 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base f809d46c10c59b3824c9be6c7ccb46db690cd441 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14120/instruction.md b/tasks/ohmyzsh__ohmyzsh-14120/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..573cc85ed1307db27d4c57b9d90d6a98ce0b6f59 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14120/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** feat(sops): introduce plugin + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +Introduce [sops](https://github.com/scaleway/scaleway-cli) plugin. + +## Other comments: + +Largely inspired by the deno plugin ;) + +This is my second attempt after :) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f809d46c10c5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14120/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14120/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4c4307e4a4dff080759128938b4f7f401a749184 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14120/solution/patch.diff @@ -0,0 +1,33 @@ +diff --git a/plugins/sops/README.md b/plugins/sops/README.md +new file mode 100644 +index 00000000..4d611e53 +--- /dev/null ++++ b/plugins/sops/README.md +@@ -0,0 +1,3 @@ ++## Sops Plugin ++ ++This plugin sets up completion for [sops](https://getsops.io). +diff --git a/plugins/sops/sops.plugin.zsh b/plugins/sops/sops.plugin.zsh +new file mode 100644 +index 00000000..69510580 +--- /dev/null ++++ b/plugins/sops/sops.plugin.zsh +@@ -0,0 +1,18 @@ ++# COMPLETION FUNCTION ++if (( ! $+commands[sops] )); then ++ return ++fi ++ ++# If the completion file doesn't exist yet, we need to autoload it and ++# bind it to `sops`. Otherwise, compinit will have already done that. ++if [[ ! -f "$ZSH_CACHE_DIR/completions/_sops" ]]; then ++ typeset -g -A _comps ++ autoload -Uz _sops ++ _comps[sops]=_sops ++fi ++ ++zmodload -F zsh/files b:zf_mv ++() { ++ local TMPPREFIX="$ZSH_CACHE_DIR/completions/._sops" ++ zf_mv -f -- =( sops completions zsh ) "$ZSH_CACHE_DIR/completions/_sops" ++} &| diff --git a/tasks/ohmyzsh__ohmyzsh-14120/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14120/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14120/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14120/task.toml b/tasks/ohmyzsh__ohmyzsh-14120/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..785d83bc9357409447e30035e9e35feb2cea942e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14120/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14120" +description = "feat(sops): introduce plugin" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "f809d46c10c59b3824c9be6c7ccb46db690cd441" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14120" +source_access = "auto" +built_at = "2026-11-16T16:09:56.908061+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:873cc59a35b5ea36a3ade67d0fbf33d8aced7feeb0c01eebbe4c98d7fc9b9365" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-28T08:24:36Z" +diff_format = "unified" +context_files = [ + "plugins/sops/README.md", + "plugins/sops/sops.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 21 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.992778+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1aebf9704ac0d8cb774ed75ca3bb0e2e7dabeb28b1cdea4e622a25545ea013c6" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14120/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14120/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14120/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14120/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14120/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..573cc85ed1307db27d4c57b9d90d6a98ce0b6f59 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14120/tests/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** feat(sops): introduce plugin + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +Introduce [sops](https://github.com/scaleway/scaleway-cli) plugin. + +## Other comments: + +Largely inspired by the deno plugin ;) + +This is my second attempt after :) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `f809d46c10c5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14120/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14120/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4c4307e4a4dff080759128938b4f7f401a749184 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14120/tests/oracle.patch @@ -0,0 +1,33 @@ +diff --git a/plugins/sops/README.md b/plugins/sops/README.md +new file mode 100644 +index 00000000..4d611e53 +--- /dev/null ++++ b/plugins/sops/README.md +@@ -0,0 +1,3 @@ ++## Sops Plugin ++ ++This plugin sets up completion for [sops](https://getsops.io). +diff --git a/plugins/sops/sops.plugin.zsh b/plugins/sops/sops.plugin.zsh +new file mode 100644 +index 00000000..69510580 +--- /dev/null ++++ b/plugins/sops/sops.plugin.zsh +@@ -0,0 +1,18 @@ ++# COMPLETION FUNCTION ++if (( ! $+commands[sops] )); then ++ return ++fi ++ ++# If the completion file doesn't exist yet, we need to autoload it and ++# bind it to `sops`. Otherwise, compinit will have already done that. ++if [[ ! -f "$ZSH_CACHE_DIR/completions/_sops" ]]; then ++ typeset -g -A _comps ++ autoload -Uz _sops ++ _comps[sops]=_sops ++fi ++ ++zmodload -F zsh/files b:zf_mv ++() { ++ local TMPPREFIX="$ZSH_CACHE_DIR/completions/._sops" ++ zf_mv -f -- =( sops completions zsh ) "$ZSH_CACHE_DIR/completions/_sops" ++} &| diff --git a/tasks/ohmyzsh__ohmyzsh-14120/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14120/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..4d891e6bc930cc7e94108cd46b03ffa796a83efd --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14120/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace f809d46c10c59b3824c9be6c7ccb46db690cd441 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14120/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14120/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14120/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14122/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14122/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..96a5f82ae7ef6ccdab9310fadf03ce07a1a421ec --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14122/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 86ef6555e068663736a33376e4055aca9c1acc89 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 86ef6555e068663736a33376e4055aca9c1acc89 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 86ef6555e068663736a33376e4055aca9c1acc89 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14122/instruction.md b/tasks/ohmyzsh__ohmyzsh-14122/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b8ef2c90d4937aa6f6bd186eff83603756b89360 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14122/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** eat(docker-compose): add `dcv`, `dcsts` and `dci` aliases + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Added `dcv`, `dcsts` and `dci` aliases into docker compose. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `86ef6555e068`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14122/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14122/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7c2d98e1b7b3eb52c0d2f7ca0e6c1a7ce65fa976 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14122/solution/patch.diff @@ -0,0 +1,33 @@ +diff --git a/plugins/docker-compose/README.md b/plugins/docker-compose/README.md +index 01d4df1c..172e9798 100644 +--- a/plugins/docker-compose/README.md ++++ b/plugins/docker-compose/README.md +@@ -17,7 +17,7 @@ plugins=(... docker-compose) + |-----------|----------------------------------|----------------------------------------------------------------------------------| + | dco | `docker-compose` | Docker-compose main command | + | dcb | `docker-compose build` | Build containers | +-| dcc | `docker-compose config` | Parse, resolve and render compose file in canonical format | ++| dcc | `docker-compose config` | Parse, resolve and render compose file in canonical format | + | dce | `docker-compose exec` | Execute command inside a container | + | dcps | `docker-compose ps` | List containers | + | dcrestart | `docker-compose restart` | Restart container | +@@ -35,3 +35,6 @@ plugins=(... docker-compose) + | dcpull | `docker-compose pull` | Pull image of a service | + | dcstart | `docker-compose start` | Start a container | + | dck | `docker-compose kill` | Kills containers | ++| dcv | `docker-compose version` | Show version information | ++| dcsts | `docker-compose stats` | Show stats of containers | ++| dci | `docker-compose images` | List images | +diff --git a/plugins/docker-compose/docker-compose.plugin.zsh b/plugins/docker-compose/docker-compose.plugin.zsh +index 97dd864b..adf6fb2f 100644 +--- a/plugins/docker-compose/docker-compose.plugin.zsh ++++ b/plugins/docker-compose/docker-compose.plugin.zsh +@@ -24,5 +24,8 @@ alias dclF="$dccmd logs -f --tail 0" + alias dcpull="$dccmd pull" + alias dcstart="$dccmd start" + alias dck="$dccmd kill" ++alias dcv="$dccmd version" ++alias dcsts="$dccmd stats" ++alias dci="$dccmd images" + + unset dccmd diff --git a/tasks/ohmyzsh__ohmyzsh-14122/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14122/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14122/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14122/task.toml b/tasks/ohmyzsh__ohmyzsh-14122/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f3c0a6deb5520754b060dc19576f43fdedfbde34 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14122/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14122" +description = "eat(docker-compose): add `dcv`, `dcsts` and `dci` aliases" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "86ef6555e068663736a33376e4055aca9c1acc89" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14122" +source_access = "auto" +built_at = "2026-11-16T16:09:56.918835+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6c4248d19543bfe462e8f2e6bbfd75be9f8a69ca479699a57fd5a19d0361f18b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-23T00:57:31Z" +diff_format = "unified" +context_files = [ + "plugins/docker-compose/README.md", + "plugins/docker-compose/docker-compose.plugin.zsh", +] +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.993245+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:80d5618b02a2b85eb9b47b1f6d5535788c3f94f1cae74ec5c46082104db7dc3a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14122/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14122/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14122/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14122/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14122/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b8ef2c90d4937aa6f6bd186eff83603756b89360 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14122/tests/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** eat(docker-compose): add `dcv`, `dcsts` and `dci` aliases + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Added `dcv`, `dcsts` and `dci` aliases into docker compose. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `86ef6555e068`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14122/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14122/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7c2d98e1b7b3eb52c0d2f7ca0e6c1a7ce65fa976 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14122/tests/oracle.patch @@ -0,0 +1,33 @@ +diff --git a/plugins/docker-compose/README.md b/plugins/docker-compose/README.md +index 01d4df1c..172e9798 100644 +--- a/plugins/docker-compose/README.md ++++ b/plugins/docker-compose/README.md +@@ -17,7 +17,7 @@ plugins=(... docker-compose) + |-----------|----------------------------------|----------------------------------------------------------------------------------| + | dco | `docker-compose` | Docker-compose main command | + | dcb | `docker-compose build` | Build containers | +-| dcc | `docker-compose config` | Parse, resolve and render compose file in canonical format | ++| dcc | `docker-compose config` | Parse, resolve and render compose file in canonical format | + | dce | `docker-compose exec` | Execute command inside a container | + | dcps | `docker-compose ps` | List containers | + | dcrestart | `docker-compose restart` | Restart container | +@@ -35,3 +35,6 @@ plugins=(... docker-compose) + | dcpull | `docker-compose pull` | Pull image of a service | + | dcstart | `docker-compose start` | Start a container | + | dck | `docker-compose kill` | Kills containers | ++| dcv | `docker-compose version` | Show version information | ++| dcsts | `docker-compose stats` | Show stats of containers | ++| dci | `docker-compose images` | List images | +diff --git a/plugins/docker-compose/docker-compose.plugin.zsh b/plugins/docker-compose/docker-compose.plugin.zsh +index 97dd864b..adf6fb2f 100644 +--- a/plugins/docker-compose/docker-compose.plugin.zsh ++++ b/plugins/docker-compose/docker-compose.plugin.zsh +@@ -24,5 +24,8 @@ alias dclF="$dccmd logs -f --tail 0" + alias dcpull="$dccmd pull" + alias dcstart="$dccmd start" + alias dck="$dccmd kill" ++alias dcv="$dccmd version" ++alias dcsts="$dccmd stats" ++alias dci="$dccmd images" + + unset dccmd diff --git a/tasks/ohmyzsh__ohmyzsh-14122/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14122/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c47bb33502e89712a9a9470ccd49fbe610d6bbbe --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14122/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 86ef6555e068663736a33376e4055aca9c1acc89 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14122/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14122/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14122/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14128/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14128/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc92fc8353224318839312c01cf5dd241dc598d3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14128/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 74965c96098134b192f00084f966b4b02438a739 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 74965c96098134b192f00084f966b4b02438a739 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 74965c96098134b192f00084f966b4b02438a739 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14128/instruction.md b/tasks/ohmyzsh__ohmyzsh-14128/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..661da8909b7fe6cb58dae2ac0b6298d865619a42 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14128/instruction.md @@ -0,0 +1,45 @@ +# Issue + +**Title:** fix(lib): protect omz_urlencode from global aliases + +## Description + +Relates to #5243 + +Global aliases are expanded at parse time anywhere on a line. When a user re-sources their zshrc, lib/functions.zsh is re-parsed while the aliases from a previous run are still defined, so common-aliases' + + alias -g P="2>&1| pygmentize -l pytb" + +rewrites omz_urlencode's option parsing into + + zparseopts -D -E -a opts r m 2>&1 | pygmentize -l pytb + +omz_termsupport_cwd calls omz_urlencode from precmd, so every prompt then prints "omz_urlencode:5: command not found: pygmentize". Quoting the specs prevents the expansion. + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- prevents the error `omz_urlencode:5: command not found: pygmentize` when reloading the shell profile multiple times. + +## Other comments: + +#5243 was closed with the advice to use `exec zsh` instead of re-sourcing, but people still reload that way. Quoting the three specs fixes it at no cost, without banning global aliases or adding `setopt no_aliases` across lib/. + +Assisted by: Claude Opus 5.5 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `74965c960981`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14128/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14128/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c9969a275676e7a4671c3a6f640de9f237f5bd2e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14128/solution/patch.diff @@ -0,0 +1,14 @@ +diff --git a/lib/functions.zsh b/lib/functions.zsh +index 330b0e3e..0a45d6a4 100644 +--- a/lib/functions.zsh ++++ b/lib/functions.zsh +@@ -178,7 +178,8 @@ function omz_urlencode() { + setopt norematchpcre + + local -a opts +- zparseopts -D -E -a opts r m P ++ # Quote the specs so global aliases (e.g. common-aliases' P) don't expand here ++ zparseopts -D -E -a opts 'r' 'm' 'P' + + local in_str="$@" + local url_str="" diff --git a/tasks/ohmyzsh__ohmyzsh-14128/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14128/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14128/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14128/task.toml b/tasks/ohmyzsh__ohmyzsh-14128/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..de4fb883bffcc5c4356247f518bb576ff0d8ddc3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14128/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14128" +description = "fix(lib): protect omz_urlencode from global aliases" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "74965c96098134b192f00084f966b4b02438a739" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14128" +source_access = "auto" +built_at = "2026-11-16T16:09:56.911405+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:c3b960ab40c3cf4053280322bd77146492ab6f80c9e6dfa6429d2458c9bea675" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-28T07:44:07Z" +diff_format = "unified" +context_files = [ + "lib/functions.zsh", +] +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.993712+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6df2a89571567469831ffaa8b2615a575449c25845dfeb4197f338842424e79c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14128/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14128/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14128/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14128/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14128/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..661da8909b7fe6cb58dae2ac0b6298d865619a42 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14128/tests/instruction.md @@ -0,0 +1,45 @@ +# Issue + +**Title:** fix(lib): protect omz_urlencode from global aliases + +## Description + +Relates to #5243 + +Global aliases are expanded at parse time anywhere on a line. When a user re-sources their zshrc, lib/functions.zsh is re-parsed while the aliases from a previous run are still defined, so common-aliases' + + alias -g P="2>&1| pygmentize -l pytb" + +rewrites omz_urlencode's option parsing into + + zparseopts -D -E -a opts r m 2>&1 | pygmentize -l pytb + +omz_termsupport_cwd calls omz_urlencode from precmd, so every prompt then prints "omz_urlencode:5: command not found: pygmentize". Quoting the specs prevents the expansion. + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- prevents the error `omz_urlencode:5: command not found: pygmentize` when reloading the shell profile multiple times. + +## Other comments: + +#5243 was closed with the advice to use `exec zsh` instead of re-sourcing, but people still reload that way. Quoting the three specs fixes it at no cost, without banning global aliases or adding `setopt no_aliases` across lib/. + +Assisted by: Claude Opus 5.5 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `74965c960981`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14128/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14128/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c9969a275676e7a4671c3a6f640de9f237f5bd2e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14128/tests/oracle.patch @@ -0,0 +1,14 @@ +diff --git a/lib/functions.zsh b/lib/functions.zsh +index 330b0e3e..0a45d6a4 100644 +--- a/lib/functions.zsh ++++ b/lib/functions.zsh +@@ -178,7 +178,8 @@ function omz_urlencode() { + setopt norematchpcre + + local -a opts +- zparseopts -D -E -a opts r m P ++ # Quote the specs so global aliases (e.g. common-aliases' P) don't expand here ++ zparseopts -D -E -a opts 'r' 'm' 'P' + + local in_str="$@" + local url_str="" diff --git a/tasks/ohmyzsh__ohmyzsh-14128/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14128/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..bed0ef5221ecbfe151f2f011933aca5c19853403 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14128/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 74965c96098134b192f00084f966b4b02438a739 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14128/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14128/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14128/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14132/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14132/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc92fc8353224318839312c01cf5dd241dc598d3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14132/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 74965c96098134b192f00084f966b4b02438a739 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 74965c96098134b192f00084f966b4b02438a739 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 74965c96098134b192f00084f966b4b02438a739 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14132/instruction.md b/tasks/ohmyzsh__ohmyzsh-14132/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1e355cdb288afd64b90fcf478c8c99f4b6fe9a0 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14132/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** chore(gradle): update to version 05693a01 + +## Description + +## Description + +Update for **gradle plugin**: update to version . +Check out the [list of changes](https://github.com/gradle/gradle-completion/compare/gradle:e7c881d...gradle:05693a0). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `74965c960981`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14132/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14132/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..cff7c8e4cb0f34f06f37ba9768b913bbcf188cde --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14132/solution/patch.diff @@ -0,0 +1,49 @@ +diff --git a/.github/dependencies.yml b/.github/dependencies.yml +index 046fdcec..7ce9f224 100644 +--- a/.github/dependencies.yml ++++ b/.github/dependencies.yml +@@ -12,7 +12,7 @@ dependencies: + plugins/gradle: + repo: gradle/gradle-completion + branch: master +- version: e7c881dbef7462bc35ad05328397e1582fe25cb8 ++ version: 05693a01fcb246bc4e8fc32a8d561dc537aaedf2 + precopy: | + set -e + find . ! -name _gradle ! -name LICENSE -delete +diff --git a/plugins/gradle/_gradle b/plugins/gradle/_gradle +index 05025ad9..58e53e7a 100644 +--- a/plugins/gradle/_gradle ++++ b/plugins/gradle/_gradle +@@ -267,6 +267,7 @@ __gradle_subcommand() { + '-Dorg.gradle.configuration-cache.problems=[Configures how the configuration cache handles problems (fail or warn). Supported values are 'warn', or 'fail' (default).]:org.gradle.configuration cache.problems:(fail warn)' \ + '-Dorg.gradle.configuration-cache.read-only=[]' \ + '-Dorg.gradle.configuration-cache.unsafe.ignore.unsupported-build-events-listeners=[]' \ ++ '-Dorg.gradle.configuration-cache.unsafe.skip-task-logging-listeners-serialization=[]' \ + '-Dorg.gradle.configuration-cache=[Enables the configuration cache. Gradle will try to reuse the build configuration from previous builds.]' \ + '-Dorg.gradle.configureondemand=[Configures necessary projects only. Gradle will attempt to reduce configuration time for large multi-project builds.]' \ + '-Dorg.gradle.console.interactive=[]' \ +@@ -296,6 +297,7 @@ __gradle_subcommand() { + '-Dorg.gradle.jvmargs=[]' \ + '-Dorg.gradle.logging.level=[]:org.gradle.logging.level:(quiet warn info debug)' \ + '-Dorg.gradle.logging.stacktrace=[]' \ ++ '-Dorg.gradle.mirror.maven.settings=[]' \ + '-Dorg.gradle.native=[]' \ + '-Dorg.gradle.parallel=[Builds projects in parallel. Gradle will attempt to determine the optimal number of executor threads to use.]:org.gradle.parallel:(true false)' \ + '-Dorg.gradle.priority=[Specifies the scheduling priority for the Gradle daemon and all processes launched by it. Supported values are 'normal' (default) or 'low'.]:org.gradle.priority:(normal low)' \ +@@ -407,6 +409,7 @@ _gradle() { + '-Dorg.gradle.configuration-cache.problems=[Configures how the configuration cache handles problems (fail or warn). Supported values are 'warn', or 'fail' (default).]:org.gradle.configuration cache.problems:(fail warn):->argument-expected' \ + '-Dorg.gradle.configuration-cache.read-only=[]:->argument-expected' \ + '-Dorg.gradle.configuration-cache.unsafe.ignore.unsupported-build-events-listeners=[]:->argument-expected' \ ++ '-Dorg.gradle.configuration-cache.unsafe.skip-task-logging-listeners-serialization=[]:->argument-expected' \ + '-Dorg.gradle.configuration-cache=[Enables the configuration cache. Gradle will try to reuse the build configuration from previous builds.]:->argument-expected' \ + '-Dorg.gradle.configureondemand=[Configures necessary projects only. Gradle will attempt to reduce configuration time for large multi-project builds.]:->argument-expected' \ + '-Dorg.gradle.console.interactive=[]:->argument-expected' \ +@@ -436,6 +439,7 @@ _gradle() { + '-Dorg.gradle.jvmargs=[]:->argument-expected' \ + '-Dorg.gradle.logging.level=[]:org.gradle.logging.level:(quiet warn info debug):->argument-expected' \ + '-Dorg.gradle.logging.stacktrace=[]:->argument-expected' \ ++ '-Dorg.gradle.mirror.maven.settings=[]:->argument-expected' \ + '-Dorg.gradle.native=[]:->argument-expected' \ + '-Dorg.gradle.parallel=[Builds projects in parallel. Gradle will attempt to determine the optimal number of executor threads to use.]:org.gradle.parallel:(true false):->argument-expected' \ + '-Dorg.gradle.priority=[Specifies the scheduling priority for the Gradle daemon and all processes launched by it. Supported values are 'normal' (default) or 'low'.]:org.gradle.priority:(normal low):->argument-expected' \ diff --git a/tasks/ohmyzsh__ohmyzsh-14132/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14132/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14132/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14132/task.toml b/tasks/ohmyzsh__ohmyzsh-14132/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c4ced4e7e3a1cce3a06697459f4afcd68b0dfa53 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14132/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14132" +description = "chore(gradle): update to version 05693a01" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "74965c96098134b192f00084f966b4b02438a739" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14132" +source_access = "auto" +built_at = "2026-11-16T16:09:56.914342+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:8c6bd625c283feefba7a4858380f7e1d3e58a7ee0a3a55ba6e590149b0fc2663" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-28T07:10:39Z" +diff_format = "unified" +context_files = [ + ".github/dependencies.yml", + "plugins/gradle/_gradle", +] +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.994221+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6df2a89571567469831ffaa8b2615a575449c25845dfeb4197f338842424e79c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14132/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14132/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14132/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14132/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14132/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b1e355cdb288afd64b90fcf478c8c99f4b6fe9a0 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14132/tests/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** chore(gradle): update to version 05693a01 + +## Description + +## Description + +Update for **gradle plugin**: update to version . +Check out the [list of changes](https://github.com/gradle/gradle-completion/compare/gradle:e7c881d...gradle:05693a0). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `74965c960981`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14132/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14132/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..cff7c8e4cb0f34f06f37ba9768b913bbcf188cde --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14132/tests/oracle.patch @@ -0,0 +1,49 @@ +diff --git a/.github/dependencies.yml b/.github/dependencies.yml +index 046fdcec..7ce9f224 100644 +--- a/.github/dependencies.yml ++++ b/.github/dependencies.yml +@@ -12,7 +12,7 @@ dependencies: + plugins/gradle: + repo: gradle/gradle-completion + branch: master +- version: e7c881dbef7462bc35ad05328397e1582fe25cb8 ++ version: 05693a01fcb246bc4e8fc32a8d561dc537aaedf2 + precopy: | + set -e + find . ! -name _gradle ! -name LICENSE -delete +diff --git a/plugins/gradle/_gradle b/plugins/gradle/_gradle +index 05025ad9..58e53e7a 100644 +--- a/plugins/gradle/_gradle ++++ b/plugins/gradle/_gradle +@@ -267,6 +267,7 @@ __gradle_subcommand() { + '-Dorg.gradle.configuration-cache.problems=[Configures how the configuration cache handles problems (fail or warn). Supported values are 'warn', or 'fail' (default).]:org.gradle.configuration cache.problems:(fail warn)' \ + '-Dorg.gradle.configuration-cache.read-only=[]' \ + '-Dorg.gradle.configuration-cache.unsafe.ignore.unsupported-build-events-listeners=[]' \ ++ '-Dorg.gradle.configuration-cache.unsafe.skip-task-logging-listeners-serialization=[]' \ + '-Dorg.gradle.configuration-cache=[Enables the configuration cache. Gradle will try to reuse the build configuration from previous builds.]' \ + '-Dorg.gradle.configureondemand=[Configures necessary projects only. Gradle will attempt to reduce configuration time for large multi-project builds.]' \ + '-Dorg.gradle.console.interactive=[]' \ +@@ -296,6 +297,7 @@ __gradle_subcommand() { + '-Dorg.gradle.jvmargs=[]' \ + '-Dorg.gradle.logging.level=[]:org.gradle.logging.level:(quiet warn info debug)' \ + '-Dorg.gradle.logging.stacktrace=[]' \ ++ '-Dorg.gradle.mirror.maven.settings=[]' \ + '-Dorg.gradle.native=[]' \ + '-Dorg.gradle.parallel=[Builds projects in parallel. Gradle will attempt to determine the optimal number of executor threads to use.]:org.gradle.parallel:(true false)' \ + '-Dorg.gradle.priority=[Specifies the scheduling priority for the Gradle daemon and all processes launched by it. Supported values are 'normal' (default) or 'low'.]:org.gradle.priority:(normal low)' \ +@@ -407,6 +409,7 @@ _gradle() { + '-Dorg.gradle.configuration-cache.problems=[Configures how the configuration cache handles problems (fail or warn). Supported values are 'warn', or 'fail' (default).]:org.gradle.configuration cache.problems:(fail warn):->argument-expected' \ + '-Dorg.gradle.configuration-cache.read-only=[]:->argument-expected' \ + '-Dorg.gradle.configuration-cache.unsafe.ignore.unsupported-build-events-listeners=[]:->argument-expected' \ ++ '-Dorg.gradle.configuration-cache.unsafe.skip-task-logging-listeners-serialization=[]:->argument-expected' \ + '-Dorg.gradle.configuration-cache=[Enables the configuration cache. Gradle will try to reuse the build configuration from previous builds.]:->argument-expected' \ + '-Dorg.gradle.configureondemand=[Configures necessary projects only. Gradle will attempt to reduce configuration time for large multi-project builds.]:->argument-expected' \ + '-Dorg.gradle.console.interactive=[]:->argument-expected' \ +@@ -436,6 +439,7 @@ _gradle() { + '-Dorg.gradle.jvmargs=[]:->argument-expected' \ + '-Dorg.gradle.logging.level=[]:org.gradle.logging.level:(quiet warn info debug):->argument-expected' \ + '-Dorg.gradle.logging.stacktrace=[]:->argument-expected' \ ++ '-Dorg.gradle.mirror.maven.settings=[]:->argument-expected' \ + '-Dorg.gradle.native=[]:->argument-expected' \ + '-Dorg.gradle.parallel=[Builds projects in parallel. Gradle will attempt to determine the optimal number of executor threads to use.]:org.gradle.parallel:(true false):->argument-expected' \ + '-Dorg.gradle.priority=[Specifies the scheduling priority for the Gradle daemon and all processes launched by it. Supported values are 'normal' (default) or 'low'.]:org.gradle.priority:(normal low):->argument-expected' \ diff --git a/tasks/ohmyzsh__ohmyzsh-14132/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14132/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..bed0ef5221ecbfe151f2f011933aca5c19853403 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14132/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 74965c96098134b192f00084f966b4b02438a739 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14132/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14132/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14132/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14133/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14133/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc92fc8353224318839312c01cf5dd241dc598d3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14133/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 74965c96098134b192f00084f966b4b02438a739 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 74965c96098134b192f00084f966b4b02438a739 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 74965c96098134b192f00084f966b4b02438a739 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14133/instruction.md b/tasks/ohmyzsh__ohmyzsh-14133/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4d374b0dd712e93d19cc6dc60b406f6ef89add72 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14133/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** chore(kube-ps1): update to version 7aaaeee5 + +## Description + +## Description + +Update for **kube-ps1 plugin**: update to version . +Check out the [list of changes](https://github.com/jonmosco/kube-ps1/compare/jonmosco:b4cd09e...jonmosco:7aaaeee). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `74965c960981`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14133/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14133/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..411010a9e73901964c48c5f3876020c6c2400f24 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14133/solution/patch.diff @@ -0,0 +1,110 @@ +diff --git a/.github/dependencies.yml b/.github/dependencies.yml +index 046fdcec..352d7a93 100644 +--- a/.github/dependencies.yml ++++ b/.github/dependencies.yml +@@ -30,7 +30,7 @@ dependencies: + plugins/kube-ps1: + repo: jonmosco/kube-ps1 + branch: master +- version: b4cd09ec8d4dc007173e28da40aeebf8eff8c87f ++ version: 7aaaeee5eaa29f920acd850ea63839d9f87b8ac5 + precopy: | + set -e + find . ! -name kube-ps1.sh ! -name LICENSE ! -name README.md -delete +diff --git a/plugins/kube-ps1/kube-ps1.plugin.zsh b/plugins/kube-ps1/kube-ps1.plugin.zsh +index 762b65c1..77b70156 100644 +--- a/plugins/kube-ps1/kube-ps1.plugin.zsh ++++ b/plugins/kube-ps1/kube-ps1.plugin.zsh +@@ -39,6 +39,7 @@ KUBE_PS1_HIDE_IF_NOCONTEXT="${KUBE_PS1_HIDE_IF_NOCONTEXT:-false}" + _KUBE_PS1_KUBECONFIG_CACHE="${KUBECONFIG}" + _KUBE_PS1_DISABLE_PATH="${HOME}/.kube/kube-ps1/disabled" + _KUBE_PS1_LAST_TIME=0 ++_KUBE_PS1_HAS_CONTEXT=false + + # Determine our shell + _kube_ps1_shell_type() { +@@ -264,15 +265,21 @@ _kube_ps1_prompt_update() { + [[ "${KUBE_PS1_ENABLED}" == "off" ]] && return $return_code + + if ! _kube_ps1_binary_check "${KUBE_PS1_BINARY}"; then +- # No ability to fetch context/namespace; display N/A. ++ # Unable to determine context availability; preserve the existing ++ # BINARY-N/A prompt instead of treating it as no context. + KUBE_PS1_CONTEXT="BINARY-N/A" + KUBE_PS1_NAMESPACE="N/A" ++ unset _KUBE_PS1_HAS_CONTEXT ++ # Refresh when the binary becomes available again. ++ _KUBE_PS1_LAST_TIME=0 + return $return_code + fi + +- if [[ "${KUBECONFIG}" != "${_KUBE_PS1_KUBECONFIG_CACHE}" ]]; then +- # User changed KUBECONFIG; unconditionally refetch. +- _KUBE_PS1_KUBECONFIG_CACHE=${KUBECONFIG} ++ if [[ "${_KUBE_PS1_LAST_TIME}" == 0 ]] || ++ [[ "${KUBECONFIG}" != "${_KUBE_PS1_KUBECONFIG_CACHE}" ]]; then ++ # Fetch initially, even if no config file exists, and whenever the ++ # user changes KUBECONFIG. ++ _KUBE_PS1_KUBECONFIG_CACHE="${KUBECONFIG}" + _kube_ps1_get_context_ns + return $return_code + fi +@@ -300,13 +307,30 @@ _kube_ps1_prompt_update() { + } + + _kube_ps1_get_context() { +- if [[ "${KUBE_PS1_CONTEXT_ENABLE}" == true ]]; then +- KUBE_PS1_CONTEXT="$(${KUBE_PS1_BINARY} config current-context 2>/dev/null)" +- KUBE_PS1_CONTEXT="${KUBE_PS1_CONTEXT:-N/A}" ++ local context + +- if [[ -n "${KUBE_PS1_CLUSTER_FUNCTION}" ]]; then +- KUBE_PS1_CONTEXT="$("${KUBE_PS1_CLUSTER_FUNCTION}" "${KUBE_PS1_CONTEXT}")" +- fi ++ # Context availability must be detected even when context display is ++ # disabled but KUBE_PS1_HIDE_IF_NOCONTEXT is enabled. ++ if [[ "${KUBE_PS1_CONTEXT_ENABLE}" != true ]] && ++ [[ "${KUBE_PS1_HIDE_IF_NOCONTEXT}" != true ]]; then ++ KUBE_PS1_CONTEXT= ++ return ++ fi ++ ++ context="$("${KUBE_PS1_BINARY}" config current-context 2>/dev/null)" ++ ++ _KUBE_PS1_HAS_CONTEXT=false ++ [[ -n "${context}" ]] && _KUBE_PS1_HAS_CONTEXT=true ++ ++ if [[ "${KUBE_PS1_CONTEXT_ENABLE}" != true ]]; then ++ KUBE_PS1_CONTEXT= ++ return ++ fi ++ ++ KUBE_PS1_CONTEXT="${context:-N/A}" ++ ++ if [[ -n "${KUBE_PS1_CLUSTER_FUNCTION}" ]]; then ++ KUBE_PS1_CONTEXT="$("${KUBE_PS1_CLUSTER_FUNCTION}" "${KUBE_PS1_CONTEXT}")" + fi + } + +@@ -325,7 +349,7 @@ _kube_ps1_get_context_ns() { + # Set the command time + if [[ "${_KUBE_PS1_SHELL}" == "bash" ]]; then + if ((BASH_VERSINFO[0] > 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] >= 2))); then +- _KUBE_PS1_LAST_TIME=$(printf '%(%s)T') ++ printf -v _KUBE_PS1_LAST_TIME '%(%s)T' -1 + else + _KUBE_PS1_LAST_TIME=$(date +%s) + fi +@@ -407,8 +431,11 @@ kubeoff() { + # Build our prompt + kube_ps1() { + [[ "${KUBE_PS1_ENABLED}" == "off" ]] && return ++ ++ [[ "${KUBE_PS1_HIDE_IF_NOCONTEXT}" == true ]] && ++ [[ "${_KUBE_PS1_HAS_CONTEXT}" == false ]] && return ++ + [[ -z "${KUBE_PS1_CONTEXT}" ]] && [[ "${KUBE_PS1_CONTEXT_ENABLE}" == true ]] && return +- [[ "${KUBE_PS1_CONTEXT}" == "N/A" ]] && [[ ${KUBE_PS1_HIDE_IF_NOCONTEXT} == true ]] && return + + local KUBE_PS1 + local KUBE_PS1_RESET_COLOR="${_KUBE_PS1_OPEN_ESC}${_KUBE_PS1_DEFAULT_FG}${_KUBE_PS1_CLOSE_ESC}" diff --git a/tasks/ohmyzsh__ohmyzsh-14133/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14133/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14133/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14133/task.toml b/tasks/ohmyzsh__ohmyzsh-14133/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..283b5457b0a89d1474d3bc22426a4c9f35d2be54 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14133/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14133" +description = "chore(kube-ps1): update to version 7aaaeee5" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "74965c96098134b192f00084f966b4b02438a739" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14133" +source_access = "auto" +built_at = "2026-11-16T16:09:56.912804+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:f8e36dd507c96196844531cef3998cd405a61682d3ee280d8128c3f15bb26ae1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-28T07:11:10Z" +diff_format = "unified" +context_files = [ + ".github/dependencies.yml", + "plugins/kube-ps1/kube-ps1.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 53 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.994688+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6df2a89571567469831ffaa8b2615a575449c25845dfeb4197f338842424e79c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14133/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14133/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14133/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14133/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14133/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4d374b0dd712e93d19cc6dc60b406f6ef89add72 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14133/tests/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** chore(kube-ps1): update to version 7aaaeee5 + +## Description + +## Description + +Update for **kube-ps1 plugin**: update to version . +Check out the [list of changes](https://github.com/jonmosco/kube-ps1/compare/jonmosco:b4cd09e...jonmosco:7aaaeee). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `74965c960981`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14133/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14133/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..411010a9e73901964c48c5f3876020c6c2400f24 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14133/tests/oracle.patch @@ -0,0 +1,110 @@ +diff --git a/.github/dependencies.yml b/.github/dependencies.yml +index 046fdcec..352d7a93 100644 +--- a/.github/dependencies.yml ++++ b/.github/dependencies.yml +@@ -30,7 +30,7 @@ dependencies: + plugins/kube-ps1: + repo: jonmosco/kube-ps1 + branch: master +- version: b4cd09ec8d4dc007173e28da40aeebf8eff8c87f ++ version: 7aaaeee5eaa29f920acd850ea63839d9f87b8ac5 + precopy: | + set -e + find . ! -name kube-ps1.sh ! -name LICENSE ! -name README.md -delete +diff --git a/plugins/kube-ps1/kube-ps1.plugin.zsh b/plugins/kube-ps1/kube-ps1.plugin.zsh +index 762b65c1..77b70156 100644 +--- a/plugins/kube-ps1/kube-ps1.plugin.zsh ++++ b/plugins/kube-ps1/kube-ps1.plugin.zsh +@@ -39,6 +39,7 @@ KUBE_PS1_HIDE_IF_NOCONTEXT="${KUBE_PS1_HIDE_IF_NOCONTEXT:-false}" + _KUBE_PS1_KUBECONFIG_CACHE="${KUBECONFIG}" + _KUBE_PS1_DISABLE_PATH="${HOME}/.kube/kube-ps1/disabled" + _KUBE_PS1_LAST_TIME=0 ++_KUBE_PS1_HAS_CONTEXT=false + + # Determine our shell + _kube_ps1_shell_type() { +@@ -264,15 +265,21 @@ _kube_ps1_prompt_update() { + [[ "${KUBE_PS1_ENABLED}" == "off" ]] && return $return_code + + if ! _kube_ps1_binary_check "${KUBE_PS1_BINARY}"; then +- # No ability to fetch context/namespace; display N/A. ++ # Unable to determine context availability; preserve the existing ++ # BINARY-N/A prompt instead of treating it as no context. + KUBE_PS1_CONTEXT="BINARY-N/A" + KUBE_PS1_NAMESPACE="N/A" ++ unset _KUBE_PS1_HAS_CONTEXT ++ # Refresh when the binary becomes available again. ++ _KUBE_PS1_LAST_TIME=0 + return $return_code + fi + +- if [[ "${KUBECONFIG}" != "${_KUBE_PS1_KUBECONFIG_CACHE}" ]]; then +- # User changed KUBECONFIG; unconditionally refetch. +- _KUBE_PS1_KUBECONFIG_CACHE=${KUBECONFIG} ++ if [[ "${_KUBE_PS1_LAST_TIME}" == 0 ]] || ++ [[ "${KUBECONFIG}" != "${_KUBE_PS1_KUBECONFIG_CACHE}" ]]; then ++ # Fetch initially, even if no config file exists, and whenever the ++ # user changes KUBECONFIG. ++ _KUBE_PS1_KUBECONFIG_CACHE="${KUBECONFIG}" + _kube_ps1_get_context_ns + return $return_code + fi +@@ -300,13 +307,30 @@ _kube_ps1_prompt_update() { + } + + _kube_ps1_get_context() { +- if [[ "${KUBE_PS1_CONTEXT_ENABLE}" == true ]]; then +- KUBE_PS1_CONTEXT="$(${KUBE_PS1_BINARY} config current-context 2>/dev/null)" +- KUBE_PS1_CONTEXT="${KUBE_PS1_CONTEXT:-N/A}" ++ local context + +- if [[ -n "${KUBE_PS1_CLUSTER_FUNCTION}" ]]; then +- KUBE_PS1_CONTEXT="$("${KUBE_PS1_CLUSTER_FUNCTION}" "${KUBE_PS1_CONTEXT}")" +- fi ++ # Context availability must be detected even when context display is ++ # disabled but KUBE_PS1_HIDE_IF_NOCONTEXT is enabled. ++ if [[ "${KUBE_PS1_CONTEXT_ENABLE}" != true ]] && ++ [[ "${KUBE_PS1_HIDE_IF_NOCONTEXT}" != true ]]; then ++ KUBE_PS1_CONTEXT= ++ return ++ fi ++ ++ context="$("${KUBE_PS1_BINARY}" config current-context 2>/dev/null)" ++ ++ _KUBE_PS1_HAS_CONTEXT=false ++ [[ -n "${context}" ]] && _KUBE_PS1_HAS_CONTEXT=true ++ ++ if [[ "${KUBE_PS1_CONTEXT_ENABLE}" != true ]]; then ++ KUBE_PS1_CONTEXT= ++ return ++ fi ++ ++ KUBE_PS1_CONTEXT="${context:-N/A}" ++ ++ if [[ -n "${KUBE_PS1_CLUSTER_FUNCTION}" ]]; then ++ KUBE_PS1_CONTEXT="$("${KUBE_PS1_CLUSTER_FUNCTION}" "${KUBE_PS1_CONTEXT}")" + fi + } + +@@ -325,7 +349,7 @@ _kube_ps1_get_context_ns() { + # Set the command time + if [[ "${_KUBE_PS1_SHELL}" == "bash" ]]; then + if ((BASH_VERSINFO[0] > 4 || (BASH_VERSINFO[0] == 4 && BASH_VERSINFO[1] >= 2))); then +- _KUBE_PS1_LAST_TIME=$(printf '%(%s)T') ++ printf -v _KUBE_PS1_LAST_TIME '%(%s)T' -1 + else + _KUBE_PS1_LAST_TIME=$(date +%s) + fi +@@ -407,8 +431,11 @@ kubeoff() { + # Build our prompt + kube_ps1() { + [[ "${KUBE_PS1_ENABLED}" == "off" ]] && return ++ ++ [[ "${KUBE_PS1_HIDE_IF_NOCONTEXT}" == true ]] && ++ [[ "${_KUBE_PS1_HAS_CONTEXT}" == false ]] && return ++ + [[ -z "${KUBE_PS1_CONTEXT}" ]] && [[ "${KUBE_PS1_CONTEXT_ENABLE}" == true ]] && return +- [[ "${KUBE_PS1_CONTEXT}" == "N/A" ]] && [[ ${KUBE_PS1_HIDE_IF_NOCONTEXT} == true ]] && return + + local KUBE_PS1 + local KUBE_PS1_RESET_COLOR="${_KUBE_PS1_OPEN_ESC}${_KUBE_PS1_DEFAULT_FG}${_KUBE_PS1_CLOSE_ESC}" diff --git a/tasks/ohmyzsh__ohmyzsh-14133/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14133/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..bed0ef5221ecbfe151f2f011933aca5c19853403 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14133/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 74965c96098134b192f00084f966b4b02438a739 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14133/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14133/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14133/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14144/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14144/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7ab6c25a1bd68cfa948774d38f4bf02fa5c24765 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14144/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 868da9cfd537266951a79e8d9fa132f6d5f276d8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 868da9cfd537266951a79e8d9fa132f6d5f276d8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 868da9cfd537266951a79e8d9fa132f6d5f276d8 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14144/instruction.md b/tasks/ohmyzsh__ohmyzsh-14144/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1679d641c8c0b07f8770eff78e01c122ef609001 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14144/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** fix(extract): support `7zz` and `7z` for 7z archives + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- `extract`: 7z archives (`.7z`, `.7z.001`, `.pk7`) were always extracted with `7za`, which fails when only the official 7-Zip is installed (e.g. `brew install sevenzip` provides `7zz` only). +- Now tries `7zz`, `7z` and `7za` in that order, so existing p7zip setups keep working. +- If none is available, prints an error and sets a failure status, so `extract -r` doesn't remove the archive. + +## Other comments: + +Tested by extracting a `.7z` archive with each of `7zz`, `7z` and `7za` available on `PATH`, and with none of them (error shown, archive kept with `-r`). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `868da9cfd537`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14144/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14144/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..ef7b4c3fd276c492517ef9fe9eda0fa5614b8e61 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14144/solution/patch.diff @@ -0,0 +1,23 @@ +diff --git a/plugins/extract/extract.plugin.zsh b/plugins/extract/extract.plugin.zsh +index 46e97f96..8f0e8bed 100755 +--- a/plugins/extract/extract.plugin.zsh ++++ b/plugins/extract/extract.plugin.zsh +@@ -119,7 +119,17 @@ EOF + fi ;; + (*.rpm) + rpm2cpio "$full_path" | cpio --quiet -id ;; +- (*.7z | *.7z.[0-9]* | *.pk7) 7za x "$full_path" ;; ++ (*.7z | *.7z.[0-9]* | *.pk7) ++ if (( $+commands[7zz] )); then ++ 7zz x "$full_path" ++ elif (( $+commands[7z] )); then ++ 7z x "$full_path" ++ elif (( $+commands[7za] )); then ++ 7za x "$full_path" ++ else ++ echo "extract: cannot extract 7z files: install 7zz, 7z or 7za" >&2 ++ success=1 ++ fi ;; + (*.deb) + command mkdir -p "control" "data" + ar vx "$full_path" > /dev/null diff --git a/tasks/ohmyzsh__ohmyzsh-14144/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14144/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14144/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14144/task.toml b/tasks/ohmyzsh__ohmyzsh-14144/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f19d220c1d20445bcd8175c9aab041e77d0e6b02 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14144/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14144" +description = "fix(extract): support `7zz` and `7z` for 7z archives" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "868da9cfd537266951a79e8d9fa132f6d5f276d8" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14144" +source_access = "auto" +built_at = "2026-11-16T16:09:56.901319+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b60d0dcfce5881f9d47da5c5a767fc06731805460d1e6943b424a36d3a35db70" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-29T09:20:43Z" +diff_format = "unified" +context_files = [ + "plugins/extract/extract.plugin.zsh", +] +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.995194+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a2d92fe20e18b9ec0914cfed61126c3862fb88a5c0dc7c670b3ab6f24500e6bc" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14144/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14144/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14144/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14144/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14144/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1679d641c8c0b07f8770eff78e01c122ef609001 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14144/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** fix(extract): support `7zz` and `7z` for 7z archives + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- `extract`: 7z archives (`.7z`, `.7z.001`, `.pk7`) were always extracted with `7za`, which fails when only the official 7-Zip is installed (e.g. `brew install sevenzip` provides `7zz` only). +- Now tries `7zz`, `7z` and `7za` in that order, so existing p7zip setups keep working. +- If none is available, prints an error and sets a failure status, so `extract -r` doesn't remove the archive. + +## Other comments: + +Tested by extracting a `.7z` archive with each of `7zz`, `7z` and `7za` available on `PATH`, and with none of them (error shown, archive kept with `-r`). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `868da9cfd537`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14144/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14144/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..ef7b4c3fd276c492517ef9fe9eda0fa5614b8e61 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14144/tests/oracle.patch @@ -0,0 +1,23 @@ +diff --git a/plugins/extract/extract.plugin.zsh b/plugins/extract/extract.plugin.zsh +index 46e97f96..8f0e8bed 100755 +--- a/plugins/extract/extract.plugin.zsh ++++ b/plugins/extract/extract.plugin.zsh +@@ -119,7 +119,17 @@ EOF + fi ;; + (*.rpm) + rpm2cpio "$full_path" | cpio --quiet -id ;; +- (*.7z | *.7z.[0-9]* | *.pk7) 7za x "$full_path" ;; ++ (*.7z | *.7z.[0-9]* | *.pk7) ++ if (( $+commands[7zz] )); then ++ 7zz x "$full_path" ++ elif (( $+commands[7z] )); then ++ 7z x "$full_path" ++ elif (( $+commands[7za] )); then ++ 7za x "$full_path" ++ else ++ echo "extract: cannot extract 7z files: install 7zz, 7z or 7za" >&2 ++ success=1 ++ fi ;; + (*.deb) + command mkdir -p "control" "data" + ar vx "$full_path" > /dev/null diff --git a/tasks/ohmyzsh__ohmyzsh-14144/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14144/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81fc59cf1b8570945106117432260a3cde6eeb84 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14144/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 868da9cfd537266951a79e8d9fa132f6d5f276d8 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14144/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14144/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14144/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14145/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14145/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7ab6c25a1bd68cfa948774d38f4bf02fa5c24765 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14145/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 868da9cfd537266951a79e8d9fa132f6d5f276d8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 868da9cfd537266951a79e8d9fa132f6d5f276d8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 868da9cfd537266951a79e8d9fa132f6d5f276d8 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14145/instruction.md b/tasks/ohmyzsh__ohmyzsh-14145/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..931a6616736cdf17bbbbd919976f4f6db63a859d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14145/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** fix(emacs): do not emit ANSI escape codes in ghostel + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Exclude the ANSI escape codes from being outputted when using ghostel in Emacs. + +## Other comments: +Tested by running zsh in ghostel in Emacs and seeing that the escape codes are no longer being printed. + +I used AI to help generate the code that checks if the value of `INSIDE_EMACS` is in the `excluded_terms` array. +... + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `868da9cfd537`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14145/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14145/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f386c16d1be43d9bb8237b4e02830fd963f7a474 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14145/solution/patch.diff @@ -0,0 +1,14 @@ +diff --git a/plugins/emacs/emacs.plugin.zsh b/plugins/emacs/emacs.plugin.zsh +index 3ed6cee1..8322d5e1 100644 +--- a/plugins/emacs/emacs.plugin.zsh ++++ b/plugins/emacs/emacs.plugin.zsh +@@ -35,7 +35,8 @@ alias eeval="$EMACS_PLUGIN_LAUNCHER --eval" + alias eframe='emacsclient --alternate-editor="" --create-frame' + + # Emacs ANSI Term tracking +-if [[ -n "$INSIDE_EMACS" ]] && [[ "$INSIDE_EMACS" != "vterm" ]]; then ++local excluded_terms=(vterm ghostel) ++if [[ -n "$INSIDE_EMACS" ]] && (( ! ${excluded_terms[(Ie)${INSIDE_EMACS%%,*}]} )); then + chpwd_emacs() { print -P "\033AnSiTc %d"; } + print -P "\033AnSiTc %d" # Track current working directory + print -P "\033AnSiTu %n" # Track username diff --git a/tasks/ohmyzsh__ohmyzsh-14145/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14145/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14145/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14145/task.toml b/tasks/ohmyzsh__ohmyzsh-14145/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5f05431aa6db1be9b091f0f1b668cd4f37728816 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14145/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14145" +description = "fix(emacs): do not emit ANSI escape codes in ghostel" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "868da9cfd537266951a79e8d9fa132f6d5f276d8" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14145" +source_access = "auto" +built_at = "2026-11-16T16:09:56.899931+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6d010d6f66e57e85a8b73bbfd09672713e8679299044896614bf1ca981236e7c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-29T09:23:21Z" +diff_format = "unified" +context_files = [ + "plugins/emacs/emacs.plugin.zsh", +] +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.995736+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a2d92fe20e18b9ec0914cfed61126c3862fb88a5c0dc7c670b3ab6f24500e6bc" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14145/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14145/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14145/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14145/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14145/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..931a6616736cdf17bbbbd919976f4f6db63a859d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14145/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** fix(emacs): do not emit ANSI escape codes in ghostel + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Exclude the ANSI escape codes from being outputted when using ghostel in Emacs. + +## Other comments: +Tested by running zsh in ghostel in Emacs and seeing that the escape codes are no longer being printed. + +I used AI to help generate the code that checks if the value of `INSIDE_EMACS` is in the `excluded_terms` array. +... + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `868da9cfd537`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14145/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14145/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f386c16d1be43d9bb8237b4e02830fd963f7a474 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14145/tests/oracle.patch @@ -0,0 +1,14 @@ +diff --git a/plugins/emacs/emacs.plugin.zsh b/plugins/emacs/emacs.plugin.zsh +index 3ed6cee1..8322d5e1 100644 +--- a/plugins/emacs/emacs.plugin.zsh ++++ b/plugins/emacs/emacs.plugin.zsh +@@ -35,7 +35,8 @@ alias eeval="$EMACS_PLUGIN_LAUNCHER --eval" + alias eframe='emacsclient --alternate-editor="" --create-frame' + + # Emacs ANSI Term tracking +-if [[ -n "$INSIDE_EMACS" ]] && [[ "$INSIDE_EMACS" != "vterm" ]]; then ++local excluded_terms=(vterm ghostel) ++if [[ -n "$INSIDE_EMACS" ]] && (( ! ${excluded_terms[(Ie)${INSIDE_EMACS%%,*}]} )); then + chpwd_emacs() { print -P "\033AnSiTc %d"; } + print -P "\033AnSiTc %d" # Track current working directory + print -P "\033AnSiTu %n" # Track username diff --git a/tasks/ohmyzsh__ohmyzsh-14145/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14145/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81fc59cf1b8570945106117432260a3cde6eeb84 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14145/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 868da9cfd537266951a79e8d9fa132f6d5f276d8 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14145/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14145/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14145/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14146/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14146/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7ab6c25a1bd68cfa948774d38f4bf02fa5c24765 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14146/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 868da9cfd537266951a79e8d9fa132f6d5f276d8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 868da9cfd537266951a79e8d9fa132f6d5f276d8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 868da9cfd537266951a79e8d9fa132f6d5f276d8 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14146/instruction.md b/tasks/ohmyzsh__ohmyzsh-14146/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..87c460bb0384ac7099fd5cc3d56d04ca0db7428a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14146/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** feat(laravel): add setting to override the php command + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [ ] I have read the contribution guide and followed all the instructions. +- [ ] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Add a `zstyle ':omz:plugins:laravel' php` setting that sets the command the aliases use to run artisan, e.g. `herd php` for Laravel Herd or `php8.4` for a specific PHP version. +- Without the setting the aliases are unchanged (`php artisan ...`). +- Document the setting in the plugin README. + +## Other comments: + +With Laravel Herd, `php` is Herd's global PHP version, while `herd php` uses the version the site is isolated to. On a site isolated to PHP 8.5 with Herd's global at 8.4, every alias currently fails with Composer's platform check: + +``` +Your Composer dependencies require a PHP version ">= 8.5.0". You are running 8.4.23. +``` + +With `zstyle ':omz:plugins:laravel' php 'herd php'` the aliases use the right version. + +The setting is read once at load time and the aliases stay plain aliases. The helper variable is namespaced (`_omz_laravel_php`) and unset afterwards, so it can't clobber a user's variable. + +I used Claude (Anthropic) to help write and test this change. I reviewed and tested the result myself. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `868da9cfd537`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14146/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14146/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..efe50cc8a1bf34375a44d1d05730122a60937501 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14146/solution/patch.diff @@ -0,0 +1,126 @@ +diff --git a/plugins/laravel/README.md b/plugins/laravel/README.md +index d808e99a..fab9502d 100644 +--- a/plugins/laravel/README.md ++++ b/plugins/laravel/README.md +@@ -6,6 +6,21 @@ This plugin adds aliases and autocompletion for Laravel [Artisan](https://larave + plugins=(... laravel) + ``` + ++## Settings ++ ++By default the aliases run `php artisan`. To use a different PHP command, such as ++`herd php` (which runs the PHP version the [Laravel Herd](https://herd.laravel.com) site ++is isolated to, instead of Herd's global version) or a specific version like `php8.4`, ++set this before Oh My Zsh is sourced: ++ ++```zsh ++zstyle ':omz:plugins:laravel' php 'herd php' ++``` ++ ++`php` in the aliases below is then replaced with that command. ++ ++## Aliases ++ + | Alias | Description | + |:-:|:-:| + | `artisan` | `php artisan` | +diff --git a/plugins/laravel/laravel.plugin.zsh b/plugins/laravel/laravel.plugin.zsh +index 4142defd..17b2d282 100644 +--- a/plugins/laravel/laravel.plugin.zsh ++++ b/plugins/laravel/laravel.plugin.zsh +@@ -1,51 +1,56 @@ + #!zsh +-alias artisan='php artisan' +-alias bob='php artisan bob::build' ++# Command used to run artisan, e.g. `herd php` or `php8.4` (default: `php`) ++zstyle -s ':omz:plugins:laravel' php _omz_laravel_php || _omz_laravel_php=php ++ ++alias artisan="$_omz_laravel_php artisan" ++alias bob="$_omz_laravel_php artisan bob::build" + + # Development +-alias pas='php artisan serve' +-alias pad='php artisan dev' +-alias pats='php artisan test' ++alias pas="$_omz_laravel_php artisan serve" ++alias pad="$_omz_laravel_php artisan dev" ++alias pats="$_omz_laravel_php artisan test" + + # Database +-alias pam='php artisan migrate' +-alias pamf='php artisan migrate:fresh' +-alias pamfs='php artisan migrate:fresh --seed' +-alias pamr='php artisan migrate:rollback' +-alias pads='php artisan db:seed' +-alias padw='php artisan db:wipe' ++alias pam="$_omz_laravel_php artisan migrate" ++alias pamf="$_omz_laravel_php artisan migrate:fresh" ++alias pamfs="$_omz_laravel_php artisan migrate:fresh --seed" ++alias pamr="$_omz_laravel_php artisan migrate:rollback" ++alias pads="$_omz_laravel_php artisan db:seed" ++alias padw="$_omz_laravel_php artisan db:wipe" + + # Makers +-alias pamm='php artisan make:model' +-alias pamc='php artisan make:controller' +-alias pams='php artisan make:seeder' +-alias pamt='php artisan make:test' +-alias pamfa='php artisan make:factory' +-alias pamp='php artisan make:policy' +-alias pame='php artisan make:event' +-alias pamj='php artisan make:job' +-alias paml='php artisan make:listener' +-alias pamn='php artisan make:notification' +-alias pampp='php artisan make:provider' +-alias pamcl='php artisan make:class' +-alias pamen='php artisan make:enum' +-alias pami='php artisan make:interface' +-alias pamtr='php artisan make:trait' +-alias pamv='php artisan make:view' +-alias pammig='php artisan make:migration' ++alias pamm="$_omz_laravel_php artisan make:model" ++alias pamc="$_omz_laravel_php artisan make:controller" ++alias pams="$_omz_laravel_php artisan make:seeder" ++alias pamt="$_omz_laravel_php artisan make:test" ++alias pamfa="$_omz_laravel_php artisan make:factory" ++alias pamp="$_omz_laravel_php artisan make:policy" ++alias pame="$_omz_laravel_php artisan make:event" ++alias pamj="$_omz_laravel_php artisan make:job" ++alias paml="$_omz_laravel_php artisan make:listener" ++alias pamn="$_omz_laravel_php artisan make:notification" ++alias pampp="$_omz_laravel_php artisan make:provider" ++alias pamcl="$_omz_laravel_php artisan make:class" ++alias pamen="$_omz_laravel_php artisan make:enum" ++alias pami="$_omz_laravel_php artisan make:interface" ++alias pamtr="$_omz_laravel_php artisan make:trait" ++alias pamv="$_omz_laravel_php artisan make:view" ++alias pammig="$_omz_laravel_php artisan make:migration" + + + # Clears +-alias pacac='php artisan cache:clear' +-alias pacoc='php artisan config:clear' +-alias pavic='php artisan view:clear' +-alias paroc='php artisan route:clear' +-alias paopc='php artisan optimize:clear' ++alias pacac="$_omz_laravel_php artisan cache:clear" ++alias pacoc="$_omz_laravel_php artisan config:clear" ++alias pavic="$_omz_laravel_php artisan view:clear" ++alias paroc="$_omz_laravel_php artisan route:clear" ++alias paopc="$_omz_laravel_php artisan optimize:clear" + + # queues +-alias paqf='php artisan queue:failed' +-alias paqft='php artisan queue:failed-table' +-alias paql='php artisan queue:listen' +-alias paqr='php artisan queue:retry' +-alias paqt='php artisan queue:table' +-alias paqw='php artisan queue:work' ++alias paqf="$_omz_laravel_php artisan queue:failed" ++alias paqft="$_omz_laravel_php artisan queue:failed-table" ++alias paql="$_omz_laravel_php artisan queue:listen" ++alias paqr="$_omz_laravel_php artisan queue:retry" ++alias paqt="$_omz_laravel_php artisan queue:table" ++alias paqw="$_omz_laravel_php artisan queue:work" ++ ++unset _omz_laravel_php diff --git a/tasks/ohmyzsh__ohmyzsh-14146/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14146/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14146/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14146/task.toml b/tasks/ohmyzsh__ohmyzsh-14146/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6b64294ccb57aff2df76a2020314abf8ca86e9fb --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14146/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14146" +description = "feat(laravel): add setting to override the php command" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "868da9cfd537266951a79e8d9fa132f6d5f276d8" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14146" +source_access = "auto" +built_at = "2026-11-16T16:09:56.887613+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6ce4cec541c15fd8abb0b0149d7fe2095d0b8a114600170546f0fe195f94bcf2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-09T14:11:18Z" +diff_format = "unified" +context_files = [ + "plugins/laravel/README.md", + "plugins/laravel/laravel.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 98 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.996313+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:a2d92fe20e18b9ec0914cfed61126c3862fb88a5c0dc7c670b3ab6f24500e6bc" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14146/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14146/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14146/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14146/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14146/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..87c460bb0384ac7099fd5cc3d56d04ca0db7428a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14146/tests/instruction.md @@ -0,0 +1,43 @@ +# Issue + +**Title:** feat(laravel): add setting to override the php command + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [ ] I have read the contribution guide and followed all the instructions. +- [ ] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Add a `zstyle ':omz:plugins:laravel' php` setting that sets the command the aliases use to run artisan, e.g. `herd php` for Laravel Herd or `php8.4` for a specific PHP version. +- Without the setting the aliases are unchanged (`php artisan ...`). +- Document the setting in the plugin README. + +## Other comments: + +With Laravel Herd, `php` is Herd's global PHP version, while `herd php` uses the version the site is isolated to. On a site isolated to PHP 8.5 with Herd's global at 8.4, every alias currently fails with Composer's platform check: + +``` +Your Composer dependencies require a PHP version ">= 8.5.0". You are running 8.4.23. +``` + +With `zstyle ':omz:plugins:laravel' php 'herd php'` the aliases use the right version. + +The setting is read once at load time and the aliases stay plain aliases. The helper variable is namespaced (`_omz_laravel_php`) and unset afterwards, so it can't clobber a user's variable. + +I used Claude (Anthropic) to help write and test this change. I reviewed and tested the result myself. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `868da9cfd537`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14146/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14146/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..efe50cc8a1bf34375a44d1d05730122a60937501 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14146/tests/oracle.patch @@ -0,0 +1,126 @@ +diff --git a/plugins/laravel/README.md b/plugins/laravel/README.md +index d808e99a..fab9502d 100644 +--- a/plugins/laravel/README.md ++++ b/plugins/laravel/README.md +@@ -6,6 +6,21 @@ This plugin adds aliases and autocompletion for Laravel [Artisan](https://larave + plugins=(... laravel) + ``` + ++## Settings ++ ++By default the aliases run `php artisan`. To use a different PHP command, such as ++`herd php` (which runs the PHP version the [Laravel Herd](https://herd.laravel.com) site ++is isolated to, instead of Herd's global version) or a specific version like `php8.4`, ++set this before Oh My Zsh is sourced: ++ ++```zsh ++zstyle ':omz:plugins:laravel' php 'herd php' ++``` ++ ++`php` in the aliases below is then replaced with that command. ++ ++## Aliases ++ + | Alias | Description | + |:-:|:-:| + | `artisan` | `php artisan` | +diff --git a/plugins/laravel/laravel.plugin.zsh b/plugins/laravel/laravel.plugin.zsh +index 4142defd..17b2d282 100644 +--- a/plugins/laravel/laravel.plugin.zsh ++++ b/plugins/laravel/laravel.plugin.zsh +@@ -1,51 +1,56 @@ + #!zsh +-alias artisan='php artisan' +-alias bob='php artisan bob::build' ++# Command used to run artisan, e.g. `herd php` or `php8.4` (default: `php`) ++zstyle -s ':omz:plugins:laravel' php _omz_laravel_php || _omz_laravel_php=php ++ ++alias artisan="$_omz_laravel_php artisan" ++alias bob="$_omz_laravel_php artisan bob::build" + + # Development +-alias pas='php artisan serve' +-alias pad='php artisan dev' +-alias pats='php artisan test' ++alias pas="$_omz_laravel_php artisan serve" ++alias pad="$_omz_laravel_php artisan dev" ++alias pats="$_omz_laravel_php artisan test" + + # Database +-alias pam='php artisan migrate' +-alias pamf='php artisan migrate:fresh' +-alias pamfs='php artisan migrate:fresh --seed' +-alias pamr='php artisan migrate:rollback' +-alias pads='php artisan db:seed' +-alias padw='php artisan db:wipe' ++alias pam="$_omz_laravel_php artisan migrate" ++alias pamf="$_omz_laravel_php artisan migrate:fresh" ++alias pamfs="$_omz_laravel_php artisan migrate:fresh --seed" ++alias pamr="$_omz_laravel_php artisan migrate:rollback" ++alias pads="$_omz_laravel_php artisan db:seed" ++alias padw="$_omz_laravel_php artisan db:wipe" + + # Makers +-alias pamm='php artisan make:model' +-alias pamc='php artisan make:controller' +-alias pams='php artisan make:seeder' +-alias pamt='php artisan make:test' +-alias pamfa='php artisan make:factory' +-alias pamp='php artisan make:policy' +-alias pame='php artisan make:event' +-alias pamj='php artisan make:job' +-alias paml='php artisan make:listener' +-alias pamn='php artisan make:notification' +-alias pampp='php artisan make:provider' +-alias pamcl='php artisan make:class' +-alias pamen='php artisan make:enum' +-alias pami='php artisan make:interface' +-alias pamtr='php artisan make:trait' +-alias pamv='php artisan make:view' +-alias pammig='php artisan make:migration' ++alias pamm="$_omz_laravel_php artisan make:model" ++alias pamc="$_omz_laravel_php artisan make:controller" ++alias pams="$_omz_laravel_php artisan make:seeder" ++alias pamt="$_omz_laravel_php artisan make:test" ++alias pamfa="$_omz_laravel_php artisan make:factory" ++alias pamp="$_omz_laravel_php artisan make:policy" ++alias pame="$_omz_laravel_php artisan make:event" ++alias pamj="$_omz_laravel_php artisan make:job" ++alias paml="$_omz_laravel_php artisan make:listener" ++alias pamn="$_omz_laravel_php artisan make:notification" ++alias pampp="$_omz_laravel_php artisan make:provider" ++alias pamcl="$_omz_laravel_php artisan make:class" ++alias pamen="$_omz_laravel_php artisan make:enum" ++alias pami="$_omz_laravel_php artisan make:interface" ++alias pamtr="$_omz_laravel_php artisan make:trait" ++alias pamv="$_omz_laravel_php artisan make:view" ++alias pammig="$_omz_laravel_php artisan make:migration" + + + # Clears +-alias pacac='php artisan cache:clear' +-alias pacoc='php artisan config:clear' +-alias pavic='php artisan view:clear' +-alias paroc='php artisan route:clear' +-alias paopc='php artisan optimize:clear' ++alias pacac="$_omz_laravel_php artisan cache:clear" ++alias pacoc="$_omz_laravel_php artisan config:clear" ++alias pavic="$_omz_laravel_php artisan view:clear" ++alias paroc="$_omz_laravel_php artisan route:clear" ++alias paopc="$_omz_laravel_php artisan optimize:clear" + + # queues +-alias paqf='php artisan queue:failed' +-alias paqft='php artisan queue:failed-table' +-alias paql='php artisan queue:listen' +-alias paqr='php artisan queue:retry' +-alias paqt='php artisan queue:table' +-alias paqw='php artisan queue:work' ++alias paqf="$_omz_laravel_php artisan queue:failed" ++alias paqft="$_omz_laravel_php artisan queue:failed-table" ++alias paql="$_omz_laravel_php artisan queue:listen" ++alias paqr="$_omz_laravel_php artisan queue:retry" ++alias paqt="$_omz_laravel_php artisan queue:table" ++alias paqw="$_omz_laravel_php artisan queue:work" ++ ++unset _omz_laravel_php diff --git a/tasks/ohmyzsh__ohmyzsh-14146/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14146/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..81fc59cf1b8570945106117432260a3cde6eeb84 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14146/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 868da9cfd537266951a79e8d9fa132f6d5f276d8 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14146/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14146/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14146/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14147/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14147/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5a15123bb7a89e3a419ffc6f693ee85d1f23a0f9 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14147/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 92bf53f1aee03a09991e112a0f291fdc9d7f5908 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 92bf53f1aee03a09991e112a0f291fdc9d7f5908 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 92bf53f1aee03a09991e112a0f291fdc9d7f5908 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14147/instruction.md b/tasks/ohmyzsh__ohmyzsh-14147/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6c0312c2d841f2f5521fb3098392f8aff3842dcc --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14147/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** fix(universalarchive): support `7zz` and `7z` for 7z archives + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- `ua 7z` now uses the first available 7-Zip binary in this order: `7zz`, `7z`, `7za`. Previously it only called `7z`, which is missing on systems that only ship `7zz` (e.g. the official 7-Zip / Homebrew `sevenzip` package) or `7za`. +- If none of them is installed, `ua` prints `ua: cannot create 7z files: install 7zz, 7z or 7za` and returns 1. +- README: updated the tool listed for the `7z` format to `7zz`,`7z`,`7za`. + +## Other comments: + +Same approach as #14144, which made this change for the `extract` plugin. + +Tested on macOS with only `7zz`, only `7z`, only `7za`, and none of them on `PATH`. The right binary was picked in each case, and the error message with exit code 1 was shown when none was available. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `92bf53f1aee0`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14147/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14147/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..8007842ef7544cdb8193eb166cd270fff3e6a61c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14147/solution/patch.diff @@ -0,0 +1,36 @@ +diff --git a/plugins/universalarchive/README.md b/plugins/universalarchive/README.md +index bcd33cea..55e1ac2b 100644 +--- a/plugins/universalarchive/README.md ++++ b/plugins/universalarchive/README.md +@@ -52,7 +52,7 @@ The plugin will generate a default archive filename based on the input: + + | Format | Description | Tool Used | + |:-----------------|:-------------------------------|:-----------------| +-| `7z` | 7zip archive | `7z` | ++| `7z` | 7zip archive | `7zz`,`7z`,`7za` | + | `bz2` | Bzip2-compressed file | `bzip2` | + | `gz` | Gzip-compressed file | `gzip` | + | `lzma` | LZMA-compressed file | `lzma` | +diff --git a/plugins/universalarchive/universalarchive.plugin.zsh b/plugins/universalarchive/universalarchive.plugin.zsh +index b287c22b..3d4968bd 100644 +--- a/plugins/universalarchive/universalarchive.plugin.zsh ++++ b/plugins/universalarchive/universalarchive.plugin.zsh +@@ -49,7 +49,17 @@ tlz (tar.lzma), txz (tar.xz), tZ (tar.Z), xz, Z, zip, and zst." + fi + + case "$ext" in +- 7z) 7z u "${output}" "${@}" ;; ++ 7z) ++ if (( $+commands[7zz] )); then ++ 7zz u "${output}" "${@}" ++ elif (( $+commands[7z] )); then ++ 7z u "${output}" "${@}" ++ elif (( $+commands[7za] )); then ++ 7za u "${output}" "${@}" ++ else ++ echo "ua: cannot create 7z files: install 7zz, 7z or 7za" >&2 ++ return 1 ++ fi ;; + bz2) bzip2 -vcf "${@}" > "${output}" ;; + gz) gzip -vcf "${@}" > "${output}" ;; + lzma) lzma -vc -T0 "${@}" > "${output}" ;; diff --git a/tasks/ohmyzsh__ohmyzsh-14147/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14147/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14147/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14147/task.toml b/tasks/ohmyzsh__ohmyzsh-14147/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..543db5a480e7c60001a2852db1cf9967d9f4789e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14147/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14147" +description = "fix(universalarchive): support `7zz` and `7z` for 7z archives" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "92bf53f1aee03a09991e112a0f291fdc9d7f5908" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14147" +source_access = "auto" +built_at = "2026-11-16T16:09:56.898514+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:38b6799450599e75b8923312d66b00958d8786d75a17398a4f91f92906c55988" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-29T15:38:41Z" +diff_format = "unified" +context_files = [ + "plugins/universalarchive/README.md", + "plugins/universalarchive/universalarchive.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 14 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:01.996820+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:62df7042423209e6ef779c638aef24c6fb3a188db6f7f53ab2714ef020f2d459" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14147/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14147/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14147/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14147/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14147/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6c0312c2d841f2f5521fb3098392f8aff3842dcc --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14147/tests/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** fix(universalarchive): support `7zz` and `7z` for 7z archives + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- `ua 7z` now uses the first available 7-Zip binary in this order: `7zz`, `7z`, `7za`. Previously it only called `7z`, which is missing on systems that only ship `7zz` (e.g. the official 7-Zip / Homebrew `sevenzip` package) or `7za`. +- If none of them is installed, `ua` prints `ua: cannot create 7z files: install 7zz, 7z or 7za` and returns 1. +- README: updated the tool listed for the `7z` format to `7zz`,`7z`,`7za`. + +## Other comments: + +Same approach as #14144, which made this change for the `extract` plugin. + +Tested on macOS with only `7zz`, only `7z`, only `7za`, and none of them on `PATH`. The right binary was picked in each case, and the error message with exit code 1 was shown when none was available. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `92bf53f1aee0`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14147/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14147/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..8007842ef7544cdb8193eb166cd270fff3e6a61c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14147/tests/oracle.patch @@ -0,0 +1,36 @@ +diff --git a/plugins/universalarchive/README.md b/plugins/universalarchive/README.md +index bcd33cea..55e1ac2b 100644 +--- a/plugins/universalarchive/README.md ++++ b/plugins/universalarchive/README.md +@@ -52,7 +52,7 @@ The plugin will generate a default archive filename based on the input: + + | Format | Description | Tool Used | + |:-----------------|:-------------------------------|:-----------------| +-| `7z` | 7zip archive | `7z` | ++| `7z` | 7zip archive | `7zz`,`7z`,`7za` | + | `bz2` | Bzip2-compressed file | `bzip2` | + | `gz` | Gzip-compressed file | `gzip` | + | `lzma` | LZMA-compressed file | `lzma` | +diff --git a/plugins/universalarchive/universalarchive.plugin.zsh b/plugins/universalarchive/universalarchive.plugin.zsh +index b287c22b..3d4968bd 100644 +--- a/plugins/universalarchive/universalarchive.plugin.zsh ++++ b/plugins/universalarchive/universalarchive.plugin.zsh +@@ -49,7 +49,17 @@ tlz (tar.lzma), txz (tar.xz), tZ (tar.Z), xz, Z, zip, and zst." + fi + + case "$ext" in +- 7z) 7z u "${output}" "${@}" ;; ++ 7z) ++ if (( $+commands[7zz] )); then ++ 7zz u "${output}" "${@}" ++ elif (( $+commands[7z] )); then ++ 7z u "${output}" "${@}" ++ elif (( $+commands[7za] )); then ++ 7za u "${output}" "${@}" ++ else ++ echo "ua: cannot create 7z files: install 7zz, 7z or 7za" >&2 ++ return 1 ++ fi ;; + bz2) bzip2 -vcf "${@}" > "${output}" ;; + gz) gzip -vcf "${@}" > "${output}" ;; + lzma) lzma -vc -T0 "${@}" > "${output}" ;; diff --git a/tasks/ohmyzsh__ohmyzsh-14147/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14147/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..1f86705925f3b4520f03e9cf469d6ccbcec1a96f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14147/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 92bf53f1aee03a09991e112a0f291fdc9d7f5908 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14147/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14147/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14147/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14152/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14152/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..373d2df970e773556de5fcb320bb2b1d760f8908 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14152/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4d4cfc287e9d887b81242c0e431b5f49f9cec5c1 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4d4cfc287e9d887b81242c0e431b5f49f9cec5c1 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4d4cfc287e9d887b81242c0e431b5f49f9cec5c1 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14152/instruction.md b/tasks/ohmyzsh__ohmyzsh-14152/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ffc7e2a02d0ec73b763d9e02a4711526ddf597b6 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14152/instruction.md @@ -0,0 +1,49 @@ +# Issue + +**Title:** fix(extract): preserve bzip2 archives and honor extraction destination + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +Plain `.bz2` extraction currently passes the absolute archive path to `pbzip2 -d` or `bunzip2`. Both decompress beside the archive and remove it, even without `-r`. This also leaves the requested `-t` destination empty. + +Stream decompressed bytes into the extraction directory, following the existing gzip/xz behavior. The shared cleanup then removes the archive only when `-r` is requested and decompression succeeds. + +Reproduction in a temporary directory after loading the extract plugin: + +```zsh +mkdir source target +printf 'payload\n' | bzip2 > source/example.txt.bz2 +extract -t target source/example.txt.bz2 +test -f source/example.txt.bz2 +cmp <(printf 'payload\n') target/example.txt +``` + +## Other comments: + +AI-assisted implementation and testing with Codex, independently reviewed by a second agent. The personal ownership/license attestation remains unchecked for the contributor; no third-party implementation was copied. No aliases added. + +Validated on Linux with zsh 5.9, bzip2 1.0.8, and pbzip2 1.1.13: + +- Real archive tests for both decompressors: 16 cases passed; the baseline failed 12. Covers relative/absolute paths, spaces, `-t`, `-r`, existing output, corrupt archives with `-r`, and an unchanged `.tar.bz2` control. +- CI-equivalent `zsh -n` check: all 592 files passed. +- `git diff --check` passed. + +The archive regression harness was run externally; it is not a new repository test dependency. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4d4cfc287e9d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14152/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14152/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..532f4117fa1c610c96bcc5b04ca39b54e4220982 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14152/solution/patch.diff @@ -0,0 +1,15 @@ +diff --git a/plugins/extract/extract.plugin.zsh b/plugins/extract/extract.plugin.zsh +index 8f0e8bed..3a576f19 100755 +--- a/plugins/extract/extract.plugin.zsh ++++ b/plugins/extract/extract.plugin.zsh +@@ -101,7 +101,9 @@ EOF + (*.tar.lz4) lz4 -c -d "$full_path" | tar xvf - ;; + (*.tar.lrz) (( $+commands[lrzuntar] )) && lrzuntar "$full_path" ;; + (*.gz) (( $+commands[pigz] )) && pigz -cdk "$full_path" > "${file:t:r}" || gunzip -ck "$full_path" > "${file:t:r}" ;; +- (*.bz2) (( $+commands[pbzip2] )) && pbzip2 -d "$full_path" || bunzip2 "$full_path" ;; ++ (*.bz2) ++ (( $+commands[pbzip2] )) && pbzip2 -cd "$full_path" > "${file:t:r}" \ ++ || bunzip2 -c "$full_path" > "${file:t:r}" ;; + (*.xz) xzcat "$full_path" > "${file:t:r}" ;; + (*.lrz) (( $+commands[lrunzip] )) && lrunzip "$full_path" ;; + (*.lz4) lz4 -d "$full_path" ;; diff --git a/tasks/ohmyzsh__ohmyzsh-14152/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14152/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14152/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14152/task.toml b/tasks/ohmyzsh__ohmyzsh-14152/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e41518badf1494a9752b9014e0c97dbc9fe847d0 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14152/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14152" +description = "fix(extract): preserve bzip2 archives and honor extraction destination" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "4d4cfc287e9d887b81242c0e431b5f49f9cec5c1" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14152" +source_access = "auto" +built_at = "2026-11-16T16:09:56.889442+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:60e1141369e451286735cdd66f04f4125aa06a76b9256a80a66d55edeb81dc0b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-09T14:01:27Z" +diff_format = "unified" +context_files = [ + "plugins/extract/extract.plugin.zsh", +] +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.997412+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:dec8d7664626be93a97b7abb8bea87215844830f4edd832972805eb3ad0c91fb" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14152/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14152/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14152/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14152/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14152/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ffc7e2a02d0ec73b763d9e02a4711526ddf597b6 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14152/tests/instruction.md @@ -0,0 +1,49 @@ +# Issue + +**Title:** fix(extract): preserve bzip2 archives and honor extraction destination + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +Plain `.bz2` extraction currently passes the absolute archive path to `pbzip2 -d` or `bunzip2`. Both decompress beside the archive and remove it, even without `-r`. This also leaves the requested `-t` destination empty. + +Stream decompressed bytes into the extraction directory, following the existing gzip/xz behavior. The shared cleanup then removes the archive only when `-r` is requested and decompression succeeds. + +Reproduction in a temporary directory after loading the extract plugin: + +```zsh +mkdir source target +printf 'payload\n' | bzip2 > source/example.txt.bz2 +extract -t target source/example.txt.bz2 +test -f source/example.txt.bz2 +cmp <(printf 'payload\n') target/example.txt +``` + +## Other comments: + +AI-assisted implementation and testing with Codex, independently reviewed by a second agent. The personal ownership/license attestation remains unchecked for the contributor; no third-party implementation was copied. No aliases added. + +Validated on Linux with zsh 5.9, bzip2 1.0.8, and pbzip2 1.1.13: + +- Real archive tests for both decompressors: 16 cases passed; the baseline failed 12. Covers relative/absolute paths, spaces, `-t`, `-r`, existing output, corrupt archives with `-r`, and an unchanged `.tar.bz2` control. +- CI-equivalent `zsh -n` check: all 592 files passed. +- `git diff --check` passed. + +The archive regression harness was run externally; it is not a new repository test dependency. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4d4cfc287e9d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14152/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14152/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..532f4117fa1c610c96bcc5b04ca39b54e4220982 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14152/tests/oracle.patch @@ -0,0 +1,15 @@ +diff --git a/plugins/extract/extract.plugin.zsh b/plugins/extract/extract.plugin.zsh +index 8f0e8bed..3a576f19 100755 +--- a/plugins/extract/extract.plugin.zsh ++++ b/plugins/extract/extract.plugin.zsh +@@ -101,7 +101,9 @@ EOF + (*.tar.lz4) lz4 -c -d "$full_path" | tar xvf - ;; + (*.tar.lrz) (( $+commands[lrzuntar] )) && lrzuntar "$full_path" ;; + (*.gz) (( $+commands[pigz] )) && pigz -cdk "$full_path" > "${file:t:r}" || gunzip -ck "$full_path" > "${file:t:r}" ;; +- (*.bz2) (( $+commands[pbzip2] )) && pbzip2 -d "$full_path" || bunzip2 "$full_path" ;; ++ (*.bz2) ++ (( $+commands[pbzip2] )) && pbzip2 -cd "$full_path" > "${file:t:r}" \ ++ || bunzip2 -c "$full_path" > "${file:t:r}" ;; + (*.xz) xzcat "$full_path" > "${file:t:r}" ;; + (*.lrz) (( $+commands[lrunzip] )) && lrunzip "$full_path" ;; + (*.lz4) lz4 -d "$full_path" ;; diff --git a/tasks/ohmyzsh__ohmyzsh-14152/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14152/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..34897c2cc2459b8fb0d266afd74f5d9aa5c9a88d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14152/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4d4cfc287e9d887b81242c0e431b5f49f9cec5c1 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14152/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14152/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14152/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14153/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14153/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..373d2df970e773556de5fcb320bb2b1d760f8908 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14153/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 4d4cfc287e9d887b81242c0e431b5f49f9cec5c1 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 4d4cfc287e9d887b81242c0e431b5f49f9cec5c1 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 4d4cfc287e9d887b81242c0e431b5f49f9cec5c1 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14153/instruction.md b/tasks/ohmyzsh__ohmyzsh-14153/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f6a1b0019a65780f4353fd60a84f63894ac7ea69 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14153/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** chore(z): update to version 7f8ff4df + +## Description + +## Description + +Update for **z plugin**: update to version . +Check out the [list of changes](https://github.com/agkozak/zsh-z/compare/agkozak:102fb78...agkozak:7f8ff4d). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4d4cfc287e9d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14153/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14153/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..512da4ea2bd4ee4637bf4e93289838883fdd992b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14153/solution/patch.diff @@ -0,0 +1,108 @@ +diff --git a/.github/dependencies.yml b/.github/dependencies.yml +index 7b3f5a4b..0349c5da 100644 +--- a/.github/dependencies.yml ++++ b/.github/dependencies.yml +@@ -46,7 +46,7 @@ dependencies: + plugins/z: + branch: master + repo: agkozak/zsh-z +- version: 102fb78036ed76feedf623907483691777a1d510 ++ version: 7f8ff4df11b50a14e3666c7cd212baa399c9b92a + precopy: | + set -e + rm -r tests +diff --git a/plugins/z/MANUAL.md b/plugins/z/MANUAL.md +index 1c8a1d22..21fc4de5 100644 +--- a/plugins/z/MANUAL.md ++++ b/plugins/z/MANUAL.md +@@ -38,6 +38,17 @@ Zsh-z is a drop-in replacement for `rupa/z` and will, by default, use the same d + + ## News + ++### v2.0.1 (October 1, 2026) ++ ++- **Database writes now work with `setopt NO_CLOBBER`.** Under `NO_CLOBBER`, ++every database write could fail with `can't clobber parameter tmpfd containing ++file descriptor 0`, even when the database already existed. That error no longer ++occurs ([#81](https://github.com/agkozak/zsh-z/issues/81)). ++- **Database and lockfile creation now works with `setopt NO_CLOBBER`.** With ++`NO_CLOBBER` set and `APPEND_CREATE` unset, Zsh-z could not create a missing ++database or lockfile. It now creates them without changing your shell options or ++losing existing directory history ([#105](https://github.com/agkozak/zsh-z/issues/105)). ++ + ### v2.0 (August 14, 2026) + + Version **2.0** is a major step forward, and these are the changes most worth knowing about: +@@ -47,7 +58,7 @@ Version **2.0** is a major step forward, and these are the changes most worth kn + - **Safer, crash-resistant concurrent writes.** Writes are now guarded by a dedicated, stable lockfile using `zsh/system` file locking, with a bounded wait for lock acquisition (the new [`ZSHZ_LOCK_TIMEOUT`](#settings), default `1` second). Write errors are handled gracefully, and locks are always released even if a write is interrupted. On Cygwin and MSYS2 a write is also retried briefly if Windows refuses it: a virus scanner or the search indexer that opens the database in the instant between its being written and its being moved into place makes the move fail, which used to lose that one directory silently. Zsh-z now retries the move briefly. + - **Your database file now has `600` permissions** -- readable and writable only by you -- so that other users on a shared system cannot read your directory history ([#92](https://github.com/agkozak/zsh-z/issues/92)). On Zsh 5+ this uses the in-process `zf_chmod` builtin; on Zsh 4.3.11 it uses a `umask`-in-a-subshell technique that avoids the fork-and-exec of an external `chmod`. + - **`COMPLETE_ALIASES` works automatically in normal setups.** Tab completion no longer breaks when you have `setopt COMPLETE_ALIASES` enabled. Zsh-z registers the alias automatically on the first Tab press, so the manual `compdef` line that earlier versions required is no longer necessary. [See below](#complete_aliases). +-- **Fixed a `can't clobber parameter tmpfd` error on some Zsh builds.** On certain Zsh builds, every database write could fail with `can't clobber parameter tmpfd containing file descriptor 0`, leaving an error at each new prompt. The file descriptor used for the temporary database file is now held in an unset scalar rather than one seeded with `0`, so the write never trips Zsh's file-descriptor-clobber guard ([#81](https://github.com/agkozak/zsh-z/issues/81)). ++- **Fixed a `can't clobber parameter tmpfd` error on some Zsh builds.** On certain Zsh builds, every database write could fail with `can't clobber parameter tmpfd containing file descriptor 0`, leaving an error at each new prompt ([#81](https://github.com/agkozak/zsh-z/issues/81)). *Correction:* the error occurs under `setopt NO_CLOBBER`, and the v2.0 change did not fix it there; v2.0.1 does. + - **A misconfigured database file no longer closes your shell -- or nags you at every prompt.** When `ZSHZ_DATA` points at a directory, or names a file without a directory, Zsh-z now reports the problem and returns instead of calling `exit`. The per-prompt `--add` stays quiet about it, so you are told once, when you actually run `z`, rather than at every prompt ([#103](https://github.com/agkozak/zsh-z/issues/103); props @ahjota). + - **`z -x` can now remove the entry for a directory that no longer exists -- and can no longer crash Zsh 4.3.11.** The removal target used to have to exist on disk, so a database entry whose directory had been deleted -- exactly the entry you most want gone -- could not be removed. `z -x /deleted/dir` (and `z -xR`) now canonicalizes the argument without requiring it to exist, resolving symlinks in as much of the path as is still present. The same change fixes a crash on Zsh 4.3.11, where an upstream bug makes `${x:A}` segfault when the top-level component of the path is missing: `z -x /gone/sub` -- or a `ZSHZ_DATA` pointing into a missing top-level directory -- could kill the shell there. + - **More robust startup and operation.** A version check on an unsupported Zsh no longer risks exiting your interactive shell. +diff --git a/plugins/z/z.plugin.zsh b/plugins/z/z.plugin.zsh +index d922fa77..b2676206 100644 +--- a/plugins/z/z.plugin.zsh ++++ b/plugins/z/z.plugin.zsh +@@ -371,16 +371,17 @@ zshz() { + # before the lock is taken, and on Cygwin/MSYS2 a concurrent writer's rename + # passes through a window in which the datafile is unlinked or delete- + # pending, so any second syscall on the path (chmod) -- or even the creating +- # open itself -- can fail spuriously. Append mode (>>) creates the file +- # without truncating one that a concurrent writer has just renamed into +- # place. The first attempt is silent; if the file still does not exist ++ # open itself -- can fail spuriously. Forced append redirection (>>|) creates ++ # the file even under NO_CLOBBER with APPEND_CREATE disabled, without ++ # truncating one that a concurrent writer has just renamed into place. ++ # The first attempt is silent; if the file still does not exist + # afterward (so no concurrent writer supplied it), retry loudly so that real + # failures (directory permissions, read-only filesystem) reach the user. + [[ -f $datafile ]] || { + mkdir -p "${datafile:h}" && +- ( umask 077; : >> "$datafile" ) 2> /dev/null || ++ ( umask 077; : >>| "$datafile" ) 2> /dev/null || + [[ -f $datafile ]] || +- ( umask 077; : >> "$datafile" ) ++ ( umask 077; : >>| "$datafile" ) + # When $ZSHZ_OWNER is set (e.g. under `sudo -s'), hand the freshly created + # file off to that user immediately, so a query-only invocation can't leave + # behind a root-owned .z that the normal-user shell can't read. `-h' so a +@@ -525,14 +526,14 @@ zshz() { + # two-inodes race the stable lockfile exists to prevent. + # Under $ZSHZ_OWNER all of this runs with root's authority on a path the + # unprivileged owner controls, and every step follows a symlink: `-f' +- # tests the target, `>>' creates a dangling one, and flock opens it. ++ # tests the target, `>>|' creates a dangling one, and flock opens it. + # $datafile survives a planted link only because the `mv' below replaces + # it outright; the lockfile is deliberately never removed, so a symlink + # here would persist and be acted on at every subsequent write. Refuse. + local _lock_owner=${ZSHZ_OWNER:-${_Z_OWNER}} + [[ -n $_lock_owner && -L $lockfile ]] && return 1 + if [[ ! -f $lockfile ]]; then +- ( umask 077; : >> "$lockfile" ) 2> /dev/null ++ ( umask 077; : >>| "$lockfile" ) 2> /dev/null + [[ -n $_lock_owner ]] && + ${ZSHZ[CHOWN]} -h "${_lock_owner}:$(id -ng "${_lock_owner}")" "$lockfile" + fi +@@ -585,13 +586,13 @@ zshz() { + # Discard entries that are incomplete or incorrectly formatted + lines=( ${(M)lines:#/*\|[[:digit:]]##[.,]#[[:digit:]]#\|[[:digit:]]##} ) + +- # Hold the fd in an *unset* scalar, not `integer tmpfd' (which seeds it +- # with 0). On some Zsh builds, `exec {tmpfd}>|...' refuses to clobber a +- # parameter already holding a number that names an open fd -- and 0 is +- # stdin, always open -- yielding "can't clobber parameter tmpfd +- # containing file descriptor 0". An empty scalar isn't a valid fd, so +- # the guard never fires. See https://github.com/agkozak/zsh-z/issues/81 ++ # Explicitly unset the local scalar before allocating a file descriptor. ++ # Under NO_CLOBBER, even an empty scalar can be treated as fd 0 (stdin), ++ # causing `exec {tmpfd}>|...' to refuse to overwrite it. The `>|' only ++ # overrides file clobber protection, not the descriptor parameter check. ++ # See https://github.com/agkozak/zsh-z/issues/81 + local tmpfd ++ unset tmpfd + case $action in + --add) + # When zf_chmod isn't available (Zsh 4.3.11), avoid the diff --git a/tasks/ohmyzsh__ohmyzsh-14153/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14153/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14153/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14153/task.toml b/tasks/ohmyzsh__ohmyzsh-14153/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c27f8a4518fc1f615c6a8e67f86c055ce759256d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14153/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14153" +description = "chore(z): update to version 7f8ff4df" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "4d4cfc287e9d887b81242c0e431b5f49f9cec5c1" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14153" +source_access = "auto" +built_at = "2026-11-16T16:09:56.895657+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:909ddad1b7be6dee887c310f85dc3e39ed97f796c8cb492af4d1f0c714ef199a" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-05T06:03:11Z" +diff_format = "unified" +context_files = [ + ".github/dependencies.yml", + "plugins/z/MANUAL.md", + "plugins/z/z.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 42 +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.998103+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:dec8d7664626be93a97b7abb8bea87215844830f4edd832972805eb3ad0c91fb" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14153/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14153/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14153/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14153/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14153/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f6a1b0019a65780f4353fd60a84f63894ac7ea69 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14153/tests/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** chore(z): update to version 7f8ff4df + +## Description + +## Description + +Update for **z plugin**: update to version . +Check out the [list of changes](https://github.com/agkozak/zsh-z/compare/agkozak:102fb78...agkozak:7f8ff4d). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `4d4cfc287e9d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14153/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14153/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..512da4ea2bd4ee4637bf4e93289838883fdd992b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14153/tests/oracle.patch @@ -0,0 +1,108 @@ +diff --git a/.github/dependencies.yml b/.github/dependencies.yml +index 7b3f5a4b..0349c5da 100644 +--- a/.github/dependencies.yml ++++ b/.github/dependencies.yml +@@ -46,7 +46,7 @@ dependencies: + plugins/z: + branch: master + repo: agkozak/zsh-z +- version: 102fb78036ed76feedf623907483691777a1d510 ++ version: 7f8ff4df11b50a14e3666c7cd212baa399c9b92a + precopy: | + set -e + rm -r tests +diff --git a/plugins/z/MANUAL.md b/plugins/z/MANUAL.md +index 1c8a1d22..21fc4de5 100644 +--- a/plugins/z/MANUAL.md ++++ b/plugins/z/MANUAL.md +@@ -38,6 +38,17 @@ Zsh-z is a drop-in replacement for `rupa/z` and will, by default, use the same d + + ## News + ++### v2.0.1 (October 1, 2026) ++ ++- **Database writes now work with `setopt NO_CLOBBER`.** Under `NO_CLOBBER`, ++every database write could fail with `can't clobber parameter tmpfd containing ++file descriptor 0`, even when the database already existed. That error no longer ++occurs ([#81](https://github.com/agkozak/zsh-z/issues/81)). ++- **Database and lockfile creation now works with `setopt NO_CLOBBER`.** With ++`NO_CLOBBER` set and `APPEND_CREATE` unset, Zsh-z could not create a missing ++database or lockfile. It now creates them without changing your shell options or ++losing existing directory history ([#105](https://github.com/agkozak/zsh-z/issues/105)). ++ + ### v2.0 (August 14, 2026) + + Version **2.0** is a major step forward, and these are the changes most worth knowing about: +@@ -47,7 +58,7 @@ Version **2.0** is a major step forward, and these are the changes most worth kn + - **Safer, crash-resistant concurrent writes.** Writes are now guarded by a dedicated, stable lockfile using `zsh/system` file locking, with a bounded wait for lock acquisition (the new [`ZSHZ_LOCK_TIMEOUT`](#settings), default `1` second). Write errors are handled gracefully, and locks are always released even if a write is interrupted. On Cygwin and MSYS2 a write is also retried briefly if Windows refuses it: a virus scanner or the search indexer that opens the database in the instant between its being written and its being moved into place makes the move fail, which used to lose that one directory silently. Zsh-z now retries the move briefly. + - **Your database file now has `600` permissions** -- readable and writable only by you -- so that other users on a shared system cannot read your directory history ([#92](https://github.com/agkozak/zsh-z/issues/92)). On Zsh 5+ this uses the in-process `zf_chmod` builtin; on Zsh 4.3.11 it uses a `umask`-in-a-subshell technique that avoids the fork-and-exec of an external `chmod`. + - **`COMPLETE_ALIASES` works automatically in normal setups.** Tab completion no longer breaks when you have `setopt COMPLETE_ALIASES` enabled. Zsh-z registers the alias automatically on the first Tab press, so the manual `compdef` line that earlier versions required is no longer necessary. [See below](#complete_aliases). +-- **Fixed a `can't clobber parameter tmpfd` error on some Zsh builds.** On certain Zsh builds, every database write could fail with `can't clobber parameter tmpfd containing file descriptor 0`, leaving an error at each new prompt. The file descriptor used for the temporary database file is now held in an unset scalar rather than one seeded with `0`, so the write never trips Zsh's file-descriptor-clobber guard ([#81](https://github.com/agkozak/zsh-z/issues/81)). ++- **Fixed a `can't clobber parameter tmpfd` error on some Zsh builds.** On certain Zsh builds, every database write could fail with `can't clobber parameter tmpfd containing file descriptor 0`, leaving an error at each new prompt ([#81](https://github.com/agkozak/zsh-z/issues/81)). *Correction:* the error occurs under `setopt NO_CLOBBER`, and the v2.0 change did not fix it there; v2.0.1 does. + - **A misconfigured database file no longer closes your shell -- or nags you at every prompt.** When `ZSHZ_DATA` points at a directory, or names a file without a directory, Zsh-z now reports the problem and returns instead of calling `exit`. The per-prompt `--add` stays quiet about it, so you are told once, when you actually run `z`, rather than at every prompt ([#103](https://github.com/agkozak/zsh-z/issues/103); props @ahjota). + - **`z -x` can now remove the entry for a directory that no longer exists -- and can no longer crash Zsh 4.3.11.** The removal target used to have to exist on disk, so a database entry whose directory had been deleted -- exactly the entry you most want gone -- could not be removed. `z -x /deleted/dir` (and `z -xR`) now canonicalizes the argument without requiring it to exist, resolving symlinks in as much of the path as is still present. The same change fixes a crash on Zsh 4.3.11, where an upstream bug makes `${x:A}` segfault when the top-level component of the path is missing: `z -x /gone/sub` -- or a `ZSHZ_DATA` pointing into a missing top-level directory -- could kill the shell there. + - **More robust startup and operation.** A version check on an unsupported Zsh no longer risks exiting your interactive shell. +diff --git a/plugins/z/z.plugin.zsh b/plugins/z/z.plugin.zsh +index d922fa77..b2676206 100644 +--- a/plugins/z/z.plugin.zsh ++++ b/plugins/z/z.plugin.zsh +@@ -371,16 +371,17 @@ zshz() { + # before the lock is taken, and on Cygwin/MSYS2 a concurrent writer's rename + # passes through a window in which the datafile is unlinked or delete- + # pending, so any second syscall on the path (chmod) -- or even the creating +- # open itself -- can fail spuriously. Append mode (>>) creates the file +- # without truncating one that a concurrent writer has just renamed into +- # place. The first attempt is silent; if the file still does not exist ++ # open itself -- can fail spuriously. Forced append redirection (>>|) creates ++ # the file even under NO_CLOBBER with APPEND_CREATE disabled, without ++ # truncating one that a concurrent writer has just renamed into place. ++ # The first attempt is silent; if the file still does not exist + # afterward (so no concurrent writer supplied it), retry loudly so that real + # failures (directory permissions, read-only filesystem) reach the user. + [[ -f $datafile ]] || { + mkdir -p "${datafile:h}" && +- ( umask 077; : >> "$datafile" ) 2> /dev/null || ++ ( umask 077; : >>| "$datafile" ) 2> /dev/null || + [[ -f $datafile ]] || +- ( umask 077; : >> "$datafile" ) ++ ( umask 077; : >>| "$datafile" ) + # When $ZSHZ_OWNER is set (e.g. under `sudo -s'), hand the freshly created + # file off to that user immediately, so a query-only invocation can't leave + # behind a root-owned .z that the normal-user shell can't read. `-h' so a +@@ -525,14 +526,14 @@ zshz() { + # two-inodes race the stable lockfile exists to prevent. + # Under $ZSHZ_OWNER all of this runs with root's authority on a path the + # unprivileged owner controls, and every step follows a symlink: `-f' +- # tests the target, `>>' creates a dangling one, and flock opens it. ++ # tests the target, `>>|' creates a dangling one, and flock opens it. + # $datafile survives a planted link only because the `mv' below replaces + # it outright; the lockfile is deliberately never removed, so a symlink + # here would persist and be acted on at every subsequent write. Refuse. + local _lock_owner=${ZSHZ_OWNER:-${_Z_OWNER}} + [[ -n $_lock_owner && -L $lockfile ]] && return 1 + if [[ ! -f $lockfile ]]; then +- ( umask 077; : >> "$lockfile" ) 2> /dev/null ++ ( umask 077; : >>| "$lockfile" ) 2> /dev/null + [[ -n $_lock_owner ]] && + ${ZSHZ[CHOWN]} -h "${_lock_owner}:$(id -ng "${_lock_owner}")" "$lockfile" + fi +@@ -585,13 +586,13 @@ zshz() { + # Discard entries that are incomplete or incorrectly formatted + lines=( ${(M)lines:#/*\|[[:digit:]]##[.,]#[[:digit:]]#\|[[:digit:]]##} ) + +- # Hold the fd in an *unset* scalar, not `integer tmpfd' (which seeds it +- # with 0). On some Zsh builds, `exec {tmpfd}>|...' refuses to clobber a +- # parameter already holding a number that names an open fd -- and 0 is +- # stdin, always open -- yielding "can't clobber parameter tmpfd +- # containing file descriptor 0". An empty scalar isn't a valid fd, so +- # the guard never fires. See https://github.com/agkozak/zsh-z/issues/81 ++ # Explicitly unset the local scalar before allocating a file descriptor. ++ # Under NO_CLOBBER, even an empty scalar can be treated as fd 0 (stdin), ++ # causing `exec {tmpfd}>|...' to refuse to overwrite it. The `>|' only ++ # overrides file clobber protection, not the descriptor parameter check. ++ # See https://github.com/agkozak/zsh-z/issues/81 + local tmpfd ++ unset tmpfd + case $action in + --add) + # When zf_chmod isn't available (Zsh 4.3.11), avoid the diff --git a/tasks/ohmyzsh__ohmyzsh-14153/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14153/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..34897c2cc2459b8fb0d266afd74f5d9aa5c9a88d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14153/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 4d4cfc287e9d887b81242c0e431b5f49f9cec5c1 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14153/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14153/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14153/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14157/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14157/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d4973126b1707b1d37b08b021b8cbbf896e69214 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14157/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d745fbf3bd49a5038e089d7d343ca89db0cbaaff 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d745fbf3bd49a5038e089d7d343ca89db0cbaaff \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d745fbf3bd49a5038e089d7d343ca89db0cbaaff \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14157/instruction.md b/tasks/ohmyzsh__ohmyzsh-14157/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4dbeb2f1a37eca14869d60edee6dc651b159757f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14157/instruction.md @@ -0,0 +1,53 @@ +# Issue + +**Title:** fix(emacs): resolve "closing brace expected" syntax error + +## Description + +## Description + +PR #14145 added logic to suppress ANSI escape codes in `vterm` and `ghostel`, but the new condition contains a syntax error. The nested parameter expansion `${INSIDE_EMACS%%,*}` inside an array subscript within the arithmetic condition `(( ))` triggers a `closing brace expected` error when the plugin loads with `INSIDE_EMACS` set. + +Because the parse error makes the whole arithmetic condition evaluate to false, the `chpwd_emacs` hook is never registered and the OSC sequences are never printed for **any** terminal — so directory tracking regressed everywhere, not only in the excluded terminals. + +### Fix + +Extract the terminal name into its own parameter before it is used in the subscript: + +```zsh +local current_term="${INSIDE_EMACS%%,*}" +if [[ -n "$INSIDE_EMACS" ]] && (( ! ${excluded_terms[(Ie)$current_term]} )); then +``` + +### Verification + +- `zsh -n plugins/emacs/emacs.plugin.zsh` passes. +- Sourcing the plugin with a mocked `emacsclient 28.2`: + - `INSIDE_EMACS=ghostel` and `INSIDE_EMACS=vterm,5.9.1` → no error, no tracking (intended). + - `INSIDE_EMACS=xterm` → no error, the `chpwd_emacs` hook is registered and OSC sequences are emitted (tracking restored). + - unset `INSIDE_EMACS` → no tracking. + +## Standards checklist + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. (N/A: no new aliases) + +## Changes + +- Fix the `closing brace expected` syntax error in the emacs plugin by extracting the terminal name into a variable before the array subscript. +- Restore ANSI directory tracking for non-excluded terminals while keeping `vterm` and `ghostel` excluded. + +## Other comments + +**AI disclosure:** I used an AI assistant to help pinpoint the zsh parsing behavior and to run the before/after verification; the one-line change was validated end-to-end by sourcing the plugin. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d745fbf3bd49`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14157/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14157/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a42bbd696994dc601c685223ecf4228cff65756c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14157/solution/patch.diff @@ -0,0 +1,14 @@ +diff --git a/plugins/emacs/emacs.plugin.zsh b/plugins/emacs/emacs.plugin.zsh +index 8322d5e1..dacde93e 100644 +--- a/plugins/emacs/emacs.plugin.zsh ++++ b/plugins/emacs/emacs.plugin.zsh +@@ -36,7 +36,8 @@ alias eframe='emacsclient --alternate-editor="" --create-frame' + + # Emacs ANSI Term tracking + local excluded_terms=(vterm ghostel) +-if [[ -n "$INSIDE_EMACS" ]] && (( ! ${excluded_terms[(Ie)${INSIDE_EMACS%%,*}]} )); then ++local current_term="${INSIDE_EMACS%%,*}" ++if [[ -n "$INSIDE_EMACS" ]] && (( ! ${excluded_terms[(Ie)$current_term]} )); then + chpwd_emacs() { print -P "\033AnSiTc %d"; } + print -P "\033AnSiTc %d" # Track current working directory + print -P "\033AnSiTu %n" # Track username diff --git a/tasks/ohmyzsh__ohmyzsh-14157/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14157/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14157/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14157/task.toml b/tasks/ohmyzsh__ohmyzsh-14157/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1c391598efa80f32772c3c64ed066864780ac22a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14157/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14157" +description = "fix(emacs): resolve \"closing brace expected\" syntax error" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "d745fbf3bd49a5038e089d7d343ca89db0cbaaff" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14157" +source_access = "auto" +built_at = "2026-11-16T16:09:56.894034+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:ade07b898b85fd294197cfbfcd7602c04b122cfeff6e1dda3de97ed0d84ed826" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-06T09:06:46Z" +diff_format = "unified" +context_files = [ + "plugins/emacs/emacs.plugin.zsh", +] +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.998707+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6febfa73de52a1c076243b58ed409ff7889f1010303ee579312d69dfade87062" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14157/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14157/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14157/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14157/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14157/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4dbeb2f1a37eca14869d60edee6dc651b159757f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14157/tests/instruction.md @@ -0,0 +1,53 @@ +# Issue + +**Title:** fix(emacs): resolve "closing brace expected" syntax error + +## Description + +## Description + +PR #14145 added logic to suppress ANSI escape codes in `vterm` and `ghostel`, but the new condition contains a syntax error. The nested parameter expansion `${INSIDE_EMACS%%,*}` inside an array subscript within the arithmetic condition `(( ))` triggers a `closing brace expected` error when the plugin loads with `INSIDE_EMACS` set. + +Because the parse error makes the whole arithmetic condition evaluate to false, the `chpwd_emacs` hook is never registered and the OSC sequences are never printed for **any** terminal — so directory tracking regressed everywhere, not only in the excluded terminals. + +### Fix + +Extract the terminal name into its own parameter before it is used in the subscript: + +```zsh +local current_term="${INSIDE_EMACS%%,*}" +if [[ -n "$INSIDE_EMACS" ]] && (( ! ${excluded_terms[(Ie)$current_term]} )); then +``` + +### Verification + +- `zsh -n plugins/emacs/emacs.plugin.zsh` passes. +- Sourcing the plugin with a mocked `emacsclient 28.2`: + - `INSIDE_EMACS=ghostel` and `INSIDE_EMACS=vterm,5.9.1` → no error, no tracking (intended). + - `INSIDE_EMACS=xterm` → no error, the `chpwd_emacs` hook is registered and OSC sequences are emitted (tracking restored). + - unset `INSIDE_EMACS` → no tracking. + +## Standards checklist + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. (N/A: no new aliases) + +## Changes + +- Fix the `closing brace expected` syntax error in the emacs plugin by extracting the terminal name into a variable before the array subscript. +- Restore ANSI directory tracking for non-excluded terminals while keeping `vterm` and `ghostel` excluded. + +## Other comments + +**AI disclosure:** I used an AI assistant to help pinpoint the zsh parsing behavior and to run the before/after verification; the one-line change was validated end-to-end by sourcing the plugin. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d745fbf3bd49`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14157/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14157/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a42bbd696994dc601c685223ecf4228cff65756c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14157/tests/oracle.patch @@ -0,0 +1,14 @@ +diff --git a/plugins/emacs/emacs.plugin.zsh b/plugins/emacs/emacs.plugin.zsh +index 8322d5e1..dacde93e 100644 +--- a/plugins/emacs/emacs.plugin.zsh ++++ b/plugins/emacs/emacs.plugin.zsh +@@ -36,7 +36,8 @@ alias eframe='emacsclient --alternate-editor="" --create-frame' + + # Emacs ANSI Term tracking + local excluded_terms=(vterm ghostel) +-if [[ -n "$INSIDE_EMACS" ]] && (( ! ${excluded_terms[(Ie)${INSIDE_EMACS%%,*}]} )); then ++local current_term="${INSIDE_EMACS%%,*}" ++if [[ -n "$INSIDE_EMACS" ]] && (( ! ${excluded_terms[(Ie)$current_term]} )); then + chpwd_emacs() { print -P "\033AnSiTc %d"; } + print -P "\033AnSiTc %d" # Track current working directory + print -P "\033AnSiTu %n" # Track username diff --git a/tasks/ohmyzsh__ohmyzsh-14157/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14157/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e66a2f54e7e517f382f4e4f78db2ecf06fc76771 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14157/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d745fbf3bd49a5038e089d7d343ca89db0cbaaff > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14157/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14157/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14157/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14158/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14158/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e42df4737dd7c0d6596dcaed84834ecd0b1356e7 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14158/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 60c9a7a839b790cd905d0fd4419435124fd1bdc0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 60c9a7a839b790cd905d0fd4419435124fd1bdc0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 60c9a7a839b790cd905d0fd4419435124fd1bdc0 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14158/instruction.md b/tasks/ohmyzsh__ohmyzsh-14158/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8687c3f8adec1b89a0d61c7132ba2d38d73d9953 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14158/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** feat(logcli): add completion plugin + +## Description + +## Changes +- Add Zsh completion for Grafana Loki's `logcli`, generated by `logcli --completion-script-zsh`. +- Cache completion atomically with `zf_mv`, following the merged `gcx` plugin and avoiding the `compinit` race discussed in #13950. +- Document activation and the cache path. + +## Testing +- Ran `zsh -n plugins/logcli/logcli.plugin.zsh` and checked the generated completion script's Zsh syntax. +- Installed `logcli` 3.7.8 and verified the plugin generates a nonempty cache file and autoloads `_logcli`. +- Ran `git diff --check`. + +AI-assisted: implementation and validation were completed with an AI coding assistant and reviewed against the existing `gcx` plugin. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `60c9a7a839b7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14158/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14158/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f90b5048a765cfa58ec8e98a9620872629cc529d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14158/solution/patch.diff @@ -0,0 +1,48 @@ +diff --git a/plugins/logcli/README.md b/plugins/logcli/README.md +new file mode 100644 +index 00000000..614766cd +--- /dev/null ++++ b/plugins/logcli/README.md +@@ -0,0 +1,18 @@ ++# logcli plugin ++ ++This plugin adds completion for [Grafana Loki's logcli](https://grafana.com/docs/loki/latest/query/logcli/). ++ ++To use it, add `logcli` to the plugins array in your zshrc file: ++ ++```zsh ++plugins=(... logcli) ++``` ++ ++This plugin does not add any aliases. ++ ++## Cache ++ ++This plugin caches the completion script and automatically updates it when the ++plugin is loaded, which is usually when you start a new terminal emulator. ++ ++The cache is stored at `$ZSH_CACHE_DIR/completions/_logcli`. +diff --git a/plugins/logcli/logcli.plugin.zsh b/plugins/logcli/logcli.plugin.zsh +new file mode 100644 +index 00000000..b37d6b76 +--- /dev/null ++++ b/plugins/logcli/logcli.plugin.zsh +@@ -0,0 +1,18 @@ ++# Autocompletion for Grafana Loki's CLI (logcli). ++if (( ! $+commands[logcli] )); then ++ return ++fi ++ ++# If the completion file doesn't exist yet, we need to autoload it and ++# bind it to `logcli`. Otherwise, compinit will have already done that. ++if [[ ! -f "$ZSH_CACHE_DIR/completions/_logcli" ]]; then ++ typeset -g -A _comps ++ autoload -Uz _logcli ++ _comps[logcli]=_logcli ++fi ++ ++zmodload -F zsh/files b:zf_mv ++() { ++ local TMPPREFIX="$ZSH_CACHE_DIR/completions/._logcli" ++ zf_mv -f -- =( logcli --completion-script-zsh ) "$ZSH_CACHE_DIR/completions/_logcli" ++} &| diff --git a/tasks/ohmyzsh__ohmyzsh-14158/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14158/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14158/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14158/task.toml b/tasks/ohmyzsh__ohmyzsh-14158/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c604ef396411f6cd91b1342d533b39a073d3a3a0 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14158/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14158" +description = "feat(logcli): add completion plugin" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "60c9a7a839b790cd905d0fd4419435124fd1bdc0" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14158" +source_access = "auto" +built_at = "2026-11-16T16:09:56.892548+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1d42a874d4cde6bb8903e7fd4724334b4ecdb20c2e04aa90f8f14b86b50214c6" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-08T23:49:21Z" +diff_format = "unified" +context_files = [ + "plugins/logcli/README.md", + "plugins/logcli/logcli.plugin.zsh", +] +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.999988+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:4da57c1217604ffa0f5d36fbdf2e3f17d0104f0003f8460acfda62b2e303c651" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14158/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14158/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14158/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14158/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14158/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8687c3f8adec1b89a0d61c7132ba2d38d73d9953 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14158/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** feat(logcli): add completion plugin + +## Description + +## Changes +- Add Zsh completion for Grafana Loki's `logcli`, generated by `logcli --completion-script-zsh`. +- Cache completion atomically with `zf_mv`, following the merged `gcx` plugin and avoiding the `compinit` race discussed in #13950. +- Document activation and the cache path. + +## Testing +- Ran `zsh -n plugins/logcli/logcli.plugin.zsh` and checked the generated completion script's Zsh syntax. +- Installed `logcli` 3.7.8 and verified the plugin generates a nonempty cache file and autoloads `_logcli`. +- Ran `git diff --check`. + +AI-assisted: implementation and validation were completed with an AI coding assistant and reviewed against the existing `gcx` plugin. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `60c9a7a839b7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14158/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14158/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f90b5048a765cfa58ec8e98a9620872629cc529d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14158/tests/oracle.patch @@ -0,0 +1,48 @@ +diff --git a/plugins/logcli/README.md b/plugins/logcli/README.md +new file mode 100644 +index 00000000..614766cd +--- /dev/null ++++ b/plugins/logcli/README.md +@@ -0,0 +1,18 @@ ++# logcli plugin ++ ++This plugin adds completion for [Grafana Loki's logcli](https://grafana.com/docs/loki/latest/query/logcli/). ++ ++To use it, add `logcli` to the plugins array in your zshrc file: ++ ++```zsh ++plugins=(... logcli) ++``` ++ ++This plugin does not add any aliases. ++ ++## Cache ++ ++This plugin caches the completion script and automatically updates it when the ++plugin is loaded, which is usually when you start a new terminal emulator. ++ ++The cache is stored at `$ZSH_CACHE_DIR/completions/_logcli`. +diff --git a/plugins/logcli/logcli.plugin.zsh b/plugins/logcli/logcli.plugin.zsh +new file mode 100644 +index 00000000..b37d6b76 +--- /dev/null ++++ b/plugins/logcli/logcli.plugin.zsh +@@ -0,0 +1,18 @@ ++# Autocompletion for Grafana Loki's CLI (logcli). ++if (( ! $+commands[logcli] )); then ++ return ++fi ++ ++# If the completion file doesn't exist yet, we need to autoload it and ++# bind it to `logcli`. Otherwise, compinit will have already done that. ++if [[ ! -f "$ZSH_CACHE_DIR/completions/_logcli" ]]; then ++ typeset -g -A _comps ++ autoload -Uz _logcli ++ _comps[logcli]=_logcli ++fi ++ ++zmodload -F zsh/files b:zf_mv ++() { ++ local TMPPREFIX="$ZSH_CACHE_DIR/completions/._logcli" ++ zf_mv -f -- =( logcli --completion-script-zsh ) "$ZSH_CACHE_DIR/completions/_logcli" ++} &| diff --git a/tasks/ohmyzsh__ohmyzsh-14158/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14158/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9011c1b8f1ba420201eeafa18f86204e28333e74 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14158/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 60c9a7a839b790cd905d0fd4419435124fd1bdc0 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14158/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14158/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14158/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14163/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14163/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e42df4737dd7c0d6596dcaed84834ecd0b1356e7 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14163/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 60c9a7a839b790cd905d0fd4419435124fd1bdc0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 60c9a7a839b790cd905d0fd4419435124fd1bdc0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 60c9a7a839b790cd905d0fd4419435124fd1bdc0 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14163/instruction.md b/tasks/ohmyzsh__ohmyzsh-14163/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f3627a308ddbe414d5bb917de856d095af2200b8 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14163/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** fix(battery): fix regex compatibility with GNU grep in macos + +## Description + +## Standards checklist + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [ ] I have read the contribution guide and followed all the instructions. +- [ ] The code follows the code style guide detailed in the wiki. +- [ ] The code is mine or it's from somewhere with an MIT-compatible license. +- [ ] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes + +- Remove unnecessary `\ ` escapes in the macOS battery plugin's `grep` and `sed` expressions. + GNU grep 3.8+ warns about these escapes (`stray \ before white space`), while BSD grep does not. + +- Replace `\d` with `[0-9]` for GNU grep compatibility + +## Other comments + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `60c9a7a839b7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14163/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14163/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..b0e6e1412e7e9fa208deb93a5b9bf6c1e89492be --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14163/solution/patch.diff @@ -0,0 +1,37 @@ +diff --git a/plugins/battery/battery.plugin.zsh b/plugins/battery/battery.plugin.zsh +index c7618f6b..dd8ab105 100644 +--- a/plugins/battery/battery.plugin.zsh ++++ b/plugins/battery/battery.plugin.zsh +@@ -25,10 +25,10 @@ if [[ "$OSTYPE" = darwin* ]]; then + echo "$(ioreg -rc AppleSmartBattery | grep -o '"Watts"=[0-9]\+' | head -1 | grep -o '[0-9]\+')W " + } + function battery_is_charging() { +- ioreg -rc AppleSmartBattery | command grep -q '^.*"ExternalConnected"\ =\ Yes' ++ ioreg -rc AppleSmartBattery | command grep -q '^.*"ExternalConnected" = Yes' + } + function battery_pct() { +- pmset -g batt | grep -Eo "\d+%" | cut -d% -f1 ++ pmset -g batt | grep -Eo "[0-9]+%" | cut -d% -f1 + } + function battery_pct_remaining() { + if battery_is_charging; then +@@ -39,8 +39,8 @@ if [[ "$OSTYPE" = darwin* ]]; then + } + function battery_time_remaining() { + local smart_battery_status="$(ioreg -rc "AppleSmartBattery")" +- if [[ $(echo $smart_battery_status | command grep -c '^.*"ExternalConnected"\ =\ No') -eq 1 ]]; then +- timeremaining=$(echo $smart_battery_status | command grep '^.*"AvgTimeToEmpty"\ =\ ' | sed -e 's/^.*"AvgTimeToEmpty"\ =\ //') ++ if [[ $(echo $smart_battery_status | command grep -c '^.*"ExternalConnected" = No') -eq 1 ]]; then ++ timeremaining=$(echo $smart_battery_status | command grep '^.*"AvgTimeToEmpty" = ' | sed -e 's/^.*"AvgTimeToEmpty" = //') + if [ $timeremaining -gt 720 ]; then + echo "::" + else +@@ -52,7 +52,7 @@ if [[ "$OSTYPE" = darwin* ]]; then + } + function battery_pct_prompt () { + local battery_pct color +- if ioreg -rc AppleSmartBattery | command grep -q '^.*"ExternalConnected"\ =\ No'; then ++ if ioreg -rc AppleSmartBattery | command grep -q '^.*"ExternalConnected" = No'; then + battery_pct=$(battery_pct_remaining) + if [[ $battery_pct -gt 50 ]]; then + color='green' diff --git a/tasks/ohmyzsh__ohmyzsh-14163/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14163/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14163/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14163/task.toml b/tasks/ohmyzsh__ohmyzsh-14163/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ddd2708cfff3aa74cf781bb916bfa0631993f32b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14163/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14163" +description = "fix(battery): fix regex compatibility with GNU grep in macos" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "60c9a7a839b790cd905d0fd4419435124fd1bdc0" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14163" +source_access = "auto" +built_at = "2026-11-16T16:09:56.891166+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:157e207836ff25c9214edd013e12a588e4b9a6178c888f15222186d40f4a0baf" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-08T23:45:22Z" +diff_format = "unified" +context_files = [ + "plugins/battery/battery.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 10 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.000662+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:4da57c1217604ffa0f5d36fbdf2e3f17d0104f0003f8460acfda62b2e303c651" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14163/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14163/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14163/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14163/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14163/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f3627a308ddbe414d5bb917de856d095af2200b8 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14163/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** fix(battery): fix regex compatibility with GNU grep in macos + +## Description + +## Standards checklist + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [ ] I have read the contribution guide and followed all the instructions. +- [ ] The code follows the code style guide detailed in the wiki. +- [ ] The code is mine or it's from somewhere with an MIT-compatible license. +- [ ] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes + +- Remove unnecessary `\ ` escapes in the macOS battery plugin's `grep` and `sed` expressions. + GNU grep 3.8+ warns about these escapes (`stray \ before white space`), while BSD grep does not. + +- Replace `\d` with `[0-9]` for GNU grep compatibility + +## Other comments + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `60c9a7a839b7`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14163/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14163/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..b0e6e1412e7e9fa208deb93a5b9bf6c1e89492be --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14163/tests/oracle.patch @@ -0,0 +1,37 @@ +diff --git a/plugins/battery/battery.plugin.zsh b/plugins/battery/battery.plugin.zsh +index c7618f6b..dd8ab105 100644 +--- a/plugins/battery/battery.plugin.zsh ++++ b/plugins/battery/battery.plugin.zsh +@@ -25,10 +25,10 @@ if [[ "$OSTYPE" = darwin* ]]; then + echo "$(ioreg -rc AppleSmartBattery | grep -o '"Watts"=[0-9]\+' | head -1 | grep -o '[0-9]\+')W " + } + function battery_is_charging() { +- ioreg -rc AppleSmartBattery | command grep -q '^.*"ExternalConnected"\ =\ Yes' ++ ioreg -rc AppleSmartBattery | command grep -q '^.*"ExternalConnected" = Yes' + } + function battery_pct() { +- pmset -g batt | grep -Eo "\d+%" | cut -d% -f1 ++ pmset -g batt | grep -Eo "[0-9]+%" | cut -d% -f1 + } + function battery_pct_remaining() { + if battery_is_charging; then +@@ -39,8 +39,8 @@ if [[ "$OSTYPE" = darwin* ]]; then + } + function battery_time_remaining() { + local smart_battery_status="$(ioreg -rc "AppleSmartBattery")" +- if [[ $(echo $smart_battery_status | command grep -c '^.*"ExternalConnected"\ =\ No') -eq 1 ]]; then +- timeremaining=$(echo $smart_battery_status | command grep '^.*"AvgTimeToEmpty"\ =\ ' | sed -e 's/^.*"AvgTimeToEmpty"\ =\ //') ++ if [[ $(echo $smart_battery_status | command grep -c '^.*"ExternalConnected" = No') -eq 1 ]]; then ++ timeremaining=$(echo $smart_battery_status | command grep '^.*"AvgTimeToEmpty" = ' | sed -e 's/^.*"AvgTimeToEmpty" = //') + if [ $timeremaining -gt 720 ]; then + echo "::" + else +@@ -52,7 +52,7 @@ if [[ "$OSTYPE" = darwin* ]]; then + } + function battery_pct_prompt () { + local battery_pct color +- if ioreg -rc AppleSmartBattery | command grep -q '^.*"ExternalConnected"\ =\ No'; then ++ if ioreg -rc AppleSmartBattery | command grep -q '^.*"ExternalConnected" = No'; then + battery_pct=$(battery_pct_remaining) + if [[ $battery_pct -gt 50 ]]; then + color='green' diff --git a/tasks/ohmyzsh__ohmyzsh-14163/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14163/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9011c1b8f1ba420201eeafa18f86204e28333e74 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14163/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 60c9a7a839b790cd905d0fd4419435124fd1bdc0 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14163/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14163/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14163/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14167/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14167/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7b97637c830ca11985eee170ce6ba106321526ba --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14167/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 9f9b28a13df35af968f0117cb142f0eba9cc6c41 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9f9b28a13df35af968f0117cb142f0eba9cc6c41 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9f9b28a13df35af968f0117cb142f0eba9cc6c41 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14167/instruction.md b/tasks/ohmyzsh__ohmyzsh-14167/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..530dcd0f240f2015d15dc29529b4666e37000c53 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14167/instruction.md @@ -0,0 +1,87 @@ +# Issue + +**Title:** feat(cli): add Shellsavers terminal animations + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +Shellsavers is a playful name for these on-demand terminal screensavers. + +Add `omz shellsaver [aquarium|logo|hermit|party]`. Running it without a scene opens the aquarium. The other scenes +show the updater's bouncing rainbow logo, a bewildered hermit crab, and a varied +dancing crowd. Any key returns to the shell. + +`omz shellsaver` appears in `omz help` and command completion, with completion for +scene names and options. `omz screensaver` remains a hidden alias. The main +README documents the commands, defaults, examples, and terminal requirements. +No plugin or configuration is needed; animation starts only when requested. +`omz shellsaver --list` lists all four scenes and marks the aquarium as the default, +without starting the animation or requiring an interactive terminal. +`--mono`/`NO_COLOR`, timed runs, and plain-text snapshots are supported. + +The renderer runs in a separate Zsh process, handles terminal resizing, and restores +terminal state on normal exit and handled signals. Runtime requirements are Zsh +5.8+, `stty`, and a compatible terminal. +The hidden `screensaver` alias delegates to `shellsaver`; it is not listed in help +or top-level command completion. + +## Demos: + +Recorded from the running Zsh renderer, with command labels added. + +### Aquarium demo + +https://github.com/user-attachments/assets/b2ec5bad-df71-4c66-a43f-f39d93ed271c + +### Rainbow logo demo + +https://github.com/user-attachments/assets/1afa4a29-7c67-460e-9fd0-c9259c554942 + +### Hermit demo + +https://github.com/user-attachments/assets/0843ff15-0305-4616-9cd3-4ea709392ae4 + +### Party demo + +https://github.com/user-attachments/assets/e9a08ebe-61c7-4b69-90f2-7ddb69e456d1 + +## Other comments: + +Developed with assistance from OpenAI Codex. + +Validation commands: + +```sh +zsh -n lib/cli.zsh +zsh -n tools/shellsaver.zsh +git diff --check +``` + +Validated locally on macOS with Zsh 5.9: all four scenes, native CLI dispatch, +terminal restoration, key/signal exits, resizing, monochrome output, and updater +rainbow colors. Linux, Zsh 5.8, and individual terminal applications still need a +compatibility pass before release. Development tests are kept outside this PR. + +This is a fun toy rather than a performance-tuned feature. While it runs, it uses roughly +15–30% of one CPU core at the largest window size. When it is not running, it costs +nothing: no startup work, no plugin, and no background process. + +Interactive Zsh completion was checked to advertise only `shellsaver`, while +completing all four scenes and options for both spellings. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9f9b28a13df3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14167/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14167/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..dfa1405533eba2f844fd022947ef16fa3f08a1d4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14167/solution/patch.diff @@ -0,0 +1,763 @@ +diff --git a/README.md b/README.md +index ad507ecb..a443e1f1 100644 +--- a/README.md ++++ b/README.md +@@ -45,6 +45,7 @@ Twitter), and join us on [Discord](https://discord.gg/ohmyzsh). + - [Using Plugins](#using-plugins) + - [Themes](#themes) + - [Selecting A Theme](#selecting-a-theme) ++ - [Shellsavers](#shellsavers) + - [FAQ](#faq) + - [Advanced Topics](#advanced-topics) + - [Advanced Installation](#advanced-installation) +@@ -241,6 +242,33 @@ If you only know which themes you don't like, you can add them similarly to an i + ZSH_THEME_RANDOM_IGNORED=(pygmalion tjkirch_mod) + ``` + ++### Shellsavers ++ ++Give your terminal a little downtime with `omz shellsaver`—our playful name for ++terminal screensavers. The aquarium is the default; choose another scene to change the mood: ++ ++```zsh ++omz shellsaver # A quiet aquarium full of sea shells ++omz shellsaver logo # The updater's rainbow logo, bouncing around ++omz shellsaver hermit # A slightly lost hermit crab ++omz shellsaver party # A rainbow stage and a dancing crowd ++``` ++ ++Press any key or Ctrl-C to return to your shell. Screensavers run only when invoked ++and restore the terminal when they exit. No plugin or configuration change is needed. ++Use `omz help` to discover the command, and Tab to complete scene names and options. ++ ++```zsh ++omz shellsaver aquarium --seconds 30 # Stop automatically after 30 seconds ++omz shellsaver logo --mono # Use the terminal's foreground color ++omz shellsaver --list # List scenes (aquarium is the default) ++omz shellsaver --help # Show all scenes and options ++``` ++ ++Requires Zsh 5.8 or newer, `stty`, and an xterm-compatible terminal with alternate-screen ++support. No additional animation package is required. `NO_COLOR` is respected. ++A window of at least 49 columns by 18 rows is recommended. ++ + ### FAQ + + If you have some more questions or issues, you might find a solution in our +diff --git a/lib/cli.zsh b/lib/cli.zsh +index c713db5d..ed4af16e 100644 +--- a/lib/cli.zsh ++++ b/lib/cli.zsh +@@ -28,12 +28,25 @@ function _omz { + 'plugin:Manage plugins' + 'pr:Manage Oh My Zsh Pull Requests' + 'reload:Reload the current zsh session' ++ 'shellsaver:Launch a whimsical terminal screensaver' + 'shop:Open the Oh My Zsh shop' + 'theme:Manage themes' + 'update:Update Oh My Zsh' + 'version:Show the version' + ) + ++ if [[ "$words[2]" == (screensaver|shellsaver) ]] && (( CURRENT > 2 )); then ++ _arguments \ ++ '1:command:' \ ++ '2::scene:(aquarium logo hermit party)' \ ++ '--list[List available scenes]' \ ++ '--mono[Use the default foreground color]' \ ++ '--seconds[Exit after a number of seconds]:seconds:' \ ++ '--snapshot[Print a plain-text still]::frame:' \ ++ '--help[Show Shellsaver help]' ++ return ++ fi ++ + if (( CURRENT == 2 )); then + _describe 'command' cmds + elif (( CURRENT == 3 )); then +@@ -174,6 +187,7 @@ Available commands: + plugin Manage plugins + pr Manage Oh My Zsh Pull Requests + reload Reload the current zsh session ++ shellsaver [scene] Launch a Shellsaver (aquarium by default) + shop Open the Oh My Zsh shop + theme Manage themes + update Update Oh My Zsh +@@ -182,6 +196,15 @@ Available commands: + EOF + } + ++function _omz::shellsaver { ++ command zsh -f "$ZSH/tools/shellsaver.zsh" "$@" ++} ++ ++# Hidden alias; only shellsaver is advertised in help and command completion. ++function _omz::screensaver { ++ _omz::shellsaver "$@" ++} ++ + function _omz::changelog { + local version=${1:-HEAD} format=${3:-"--text"} + +diff --git a/tools/shellsaver.zsh b/tools/shellsaver.zsh +new file mode 100644 +index 00000000..4eb2c84b +--- /dev/null ++++ b/tools/shellsaver.zsh +@@ -0,0 +1,657 @@ ++#!/usr/bin/env zsh ++# Shared on-demand renderer for `omz shellsaver `. ++# The CLI launches a separate Zsh process, keeping all state out of the caller. ++{ ++ emulate -L zsh ++ setopt extendedglob ++ unsetopt multibyte ++ ++ integer tick=0 width=96 height=28 resized=1 active=0 seconds_limit=0 ++ integer mono=0 snapshot=0 scene_selected=0 ++ local saved_tty='' key='' blank='' result='' scene='' ++ local -a canvas inks palette ++ ++ _zshell_list() { ++ print -r -- 'aquarium Sea shells, a ~ hermit crab, and a quiet current (default). ++logo The Oh My Zsh wordmark takes a bouncing coffee break. ++hermit A bewildered hermit crab tries to find its working directory. ++party A rainbow terminal stage and a crowd of dancing shell fans.' ++ } ++ ++ _zshell_usage() { ++ print -r -- 'Oh My Zsh / experimental Shellsavers ++ ++Usage: omz shellsaver [aquarium|logo|hermit|party] [--mono] [--seconds N] ++ omz shellsaver [aquarium|logo|hermit|party] --snapshot [FRAME] ++ omz shellsaver --list ++' ++ _zshell_list ++ print -r -- ' ++Any key returns to the shell. Ctrl-C also exits safely. ++--list List available scenes and the default. ++--mono Use the terminal default foreground color. ++--seconds N Exit automatically after 1-3600 seconds. ++--snapshot Print a still at 96 columns x 28 rows (no terminal needed). ++ ++Requires Zsh 5.8+, stty, and an xterm-compatible terminal with an alternate screen. ++Nothing is installed or enabled automatically.' ++ } ++ case "${1-}" in ++ --help|-h) _zshell_usage; exit 0 ;; ++ ''|--*) scene=aquarium ;; ++ aquarium|logo|hermit|party) scene=$1; scene_selected=1; shift ;; ++ *) print -u2 -r -- "omz shellsaver: unknown scene: $1 (choose aquarium, logo, hermit, or party)"; exit 2 ;; ++ esac ++ ++ while (( $# )); do ++ case "$1" in ++ aquarium|logo|hermit|party) ++ if (( scene_selected )); then ++ print -u2 -r -- 'omz shellsaver: choose only one scene (try --help)' ++ exit 2 ++ fi ++ scene=$1; scene_selected=1 ;; ++ --help|-h) _zshell_usage; exit 0 ;; ++ --list) _zshell_list; exit 0 ;; ++ --mono) mono=1 ;; ++ --seconds) ++ shift ++ if [[ $1 != <1-3600> ]]; then ++ print -u2 -r -- 'omz shellsaver: --seconds requires an integer from 1 to 3600' ++ exit 2 ++ fi ++ seconds_limit=$1 ;; ++ --snapshot) ++ snapshot=1 ++ if [[ ${2-} == <0-100000> ]]; then tick=$2; shift; fi ;; ++ *) print -u2 -r -- "omz shellsaver: unknown argument: $1 (try --help)"; exit 2 ;; ++ esac ++ shift ++ done ++ ++ # Paint into separate ASCII text and color planes. Clip before slicing so a ++ # creature partly outside the viewport never wraps onto another terminal row. ++ _zshell_put() { ++ integer x=$1 y=$2 ink=$3 count skip ++ local text=$4 prefix='' suffix='' iprefix='' isuffix='' ++ (( y >= 1 && y <= height && x <= width )) || return 0 ++ if (( x < 1 )); then ++ skip=$(( 2 - x )) ++ (( skip <= ${#text} )) || return 0 ++ text=${text[$skip,-1]} ++ x=1 ++ fi ++ count=$(( width - x + 1 )) ++ text=${text[1,$count]} ++ count=${#text} ++ (( count )) || return 0 ++ if (( x > 1 )); then ++ prefix=${canvas[$y][1,$((x-1))]} ++ iprefix=${inks[$y][1,$((x-1))]} ++ fi ++ if (( x + count <= width )); then ++ suffix=${canvas[$y][$((x+count)),-1]} ++ isuffix=${inks[$y][$((x+count)),-1]} ++ fi ++ canvas[$y]="$prefix$text$suffix" ++ inks[$y]="$iprefix${(pl:$count::$ink:)}$isuffix" ++ } ++ ++ _zshell_sprite() { ++ integer sx=$1 sy=$2 color=$3 ++ shift 3 ++ local line ++ for line in "$@"; do ++ _zshell_put $sx $sy $color "$line" ++ (( sy++ )) ++ done ++ } ++ ++ _zshell_logo() { ++ # The full-size artwork and per-letter color bands match tools/upgrade.sh. ++ # A compact badge preserves the bounce in narrower terminal windows. ++ local -a logo logo_inks quips ++ local line glyph bands run ++ integer logo_width=0 logo_height span_x span_y px py x y color i j n offset ++ logo=( ++ ' __ __ ' ++ ' ____ / /_ ____ ___ __ __ ____ _____/ /_ ' ++ ' / __ \/ __ \ / __ `__ \/ / / / /_ / / ___/ __ \ ' ++ '/ /_/ / / / / / / / / / / /_/ / / /_(__ ) / / / ' ++ '\____/_/ /_/ /_/ /_/ /_/\__, / /___/____/_/ /_/ ' ++ ' /____/ ' ++ ) ++ logo_inks=( ++ 11111111122222222333333333334444444455555556666677777 ++ 11111111222222223333333333344444444555555566666777777 ++ 11111112222222233333333333444444445555555666666777777 ++ 11111112222222333333333333444444455555556666667777777 ++ 11111122222223333333333334444444555555556666677777777 ++ 11112222222233333333333444444445555555666667777777777 ++ ) ++ if (( width < 64 )); then ++ logo=( '.------------------.' '| Oh My Zsh |' '| ~ >_ |' "'------------------'" ) ++ logo_inks=() ++ for line in "${logo[@]}"; do ++ bands='' ++ for (( j=1; j<=${#line}; j++ )); do ++ bands+=$((1+(j-1)*7/${#line})) ++ done ++ logo_inks+=( "$bands" ) ++ done ++ fi ++ for line in "${logo[@]}"; do ++ (( ${#line} > logo_width )) && logo_width=${#line} ++ done ++ logo_height=${#logo} ++ span_x=$(( width-logo_width-4 )) ++ span_y=$(( height-logo_height-8 )) ++ px=$(( (tick/2+span_x/2) % (2*span_x) )) ++ py=$(( (tick/6+span_y/2) % (2*span_y) )) ++ x=$(( 3 + (px <= span_x ? px : 2*span_x-px) )) ++ y=$(( 5 + (py <= span_y ? py : 2*span_y-py) )) ++ ++ _zshell_put 3 2 1 'O H M Y Z S H' ++ _zshell_put $((width-17)) 2 0 'prompt on a break' ++ for (( i=0; i_' ++ if (( (px == 0 || px == span_x) && (py == 0 || py == span_y) )); then ++ _zshell_put $((x-2)) $((y-1)) 3 '*' ++ _zshell_put $((x+logo_width+1)) $((y-1)) 3 '*' ++ _zshell_put $(( (width-17)/2 )) $((height-2)) 3 'corner committed!' ++ else ++ quips=( 'home is where the ~ is' 'plugins on a coffee break' 'a delightful little detour' 'your prompt will be right back' ) ++ line=${quips[$((1+tick/80%${#quips}))]} ++ _zshell_put $(( (width-${#line})/2 )) $((height-2)) 0 "$line" ++ fi ++ _zshell_put 3 $height 0 'SCREENSAVER / LOGO' ++ _zshell_put $((width-21)) $height 0 'any key: back to work' ++ } ++ ++ _zshell_hermit() { ++ integer beat=$((tick/40%8)) within=$((tick%40)) shuffle=0 x y i ++ local left_eye='(o )' right_eye='(o )' mouth='._.' thought='...' legs ++ # Long, still looks make the tiny blinks and indecisive steps more visible. ++ case $beat in ++ 0) thought='...where was I going?' ;; ++ 1) left_eye='( o)'; right_eye='( o)'; thought='...over there?' ;; ++ 2) left_eye='(O )'; right_eye='( O)'; mouth=' o '; thought='pwd...?' ;; ++ 3) left_eye='( o)'; right_eye='(o )'; mouth='-_-'; thought='I brought home. Now what?' ;; ++ 4) left_eye='( o)'; right_eye='( o)'; shuffle=$((within/10)); thought='maybe this way.' ;; ++ 5) left_eye='( o)'; right_eye='(o )'; shuffle=3; thought='wrong directory.' ;; ++ 6) shuffle=$((3-within/10)); thought='cd .. ?' ;; ++ 7) left_eye='( ^)'; right_eye='(^ )'; mouth=' u '; thought='~ sweet ~ ...wait.' ;; ++ esac ++ # Short blinks run independently of the longer expression cycle. ++ if (( tick%73 >= 71 )); then left_eye='( -)'; right_eye='(- )'; fi ++ x=$(( (width-42)/2 + shuffle )) ++ y=$(( (height-12)/2 + 1 )) ++ _zshell_put 3 2 1 'O H M Y Z S H' ++ _zshell_put $((width-21)) 2 0 'a little shell-shocked' ++ # Photo-inspired three-quarter silhouette: tapered shell whorls behind ++ # the exposed head, unequal eyestalks, antennae and a hanging front claw. ++ _zshell_sprite $x $y 3 \ ++ ' __...---.' \ ++ " _.-' .--. '." \ ++ " .-' .' '. \\" \ ++ " .' _.-./ ~ \ |" \ ++ " / .' \ / |" \ ++ "/ / .-. |'-----' /" \ ++ '| ( ( @ ) / /' \ ++ "\ \ '-' .' .'" \ ++ " '-._'--'______.-'" ++ # Staggered eyes on stalks; the small head emerges from the shell opening. ++ _zshell_put $((x+25)) $((y+2)) 5 "$left_eye" ++ _zshell_put $((x+32)) $((y+1)) 5 "$right_eye" ++ _zshell_put $((x+27)) $((y+3)) 4 '|' ++ _zshell_put $((x+27)) $((y+4)) 4 '|' ++ _zshell_put $((x+33)) $((y+2)) 4 '/' ++ _zshell_put $((x+32)) $((y+3)) 4 '/' ++ _zshell_put $((x+31)) $((y+4)) 4 '/' ++ _zshell_put $((x+36)) $((y+3)) 5 "_.-'" ++ _zshell_put $((x+33)) $((y+4)) 5 ".-'" ++ _zshell_put $((x+32)) $((y+5)) 5 '/' ++ _zshell_put $((x+22)) $((y+5)) 4 '/___' ++ _zshell_put $((x+21)) $((y+6)) 4 '\___' ++ _zshell_put $((x+20)) $((y+7)) 4 '\__' ++ _zshell_put $((x+26)) $((y+5)) 4 '.----.' ++ _zshell_put $((x+25)) $((y+6)) 4 '/ \' ++ _zshell_put $((x+23)) $((y+7)) 4 '__\______/' ++ _zshell_put $((x+21)) $((y+8)) 4 '\___/ /\ \__' ++ _zshell_put $((x+27)) $((y+6)) 5 "$mouth" ++ # Legs bend down and forward instead of spreading symmetrically sideways. ++ _zshell_put $((x+18)) $((y+9)) 4 '\___/ / \___' ++ _zshell_put $((x+16)) $((y+10)) 4 '___/ / \' ++ legs=' _/____/ \_' ++ if (( (beat == 4 || beat == 6) && within/3%2 )); then ++ legs=' /___/ _/' ++ fi ++ _zshell_put $x $((y+11)) 4 "$legs" ++ # The big claw hangs in front. The much smaller claw tucks under the face. ++ if (( beat == 3 )); then ++ _zshell_sprite $((x+35)) $((y+7)) 4 ' __ ' '/ \' '| / |' ' V V ' ++ _zshell_put $((x+32)) $((y+6)) 4 '()' ++ else ++ _zshell_sprite $((x+35)) $((y+8)) 4 ' __ ' '/ \' '| / |' ' V V ' ++ _zshell_put $((x+30)) $((y+8)) 4 '()' ++ fi ++ if (( beat == 2 || beat == 5 )); then ++ _zshell_put $((x+39)) $y 1 '?' ++ fi ++ if (( height >= 24 )); then ++ for (( i=3; i= 120 )); then ++ scale=2 ++ fi ++ letters=( O H M Y Z S H ) ++ letter_colors=( 4 3 6 1 7 2 4 ) ++ logo_width=$(( (7*glyph_width+6+4)*scale )) ++ logo_x=$(( (width-logo_width)/2+1 )) ++ logo_y=$(( height/4 )); (( logo_y < 4 )) && logo_y=4 ++ ++ # A terminal window behind the crowd, including tiny window controls. ++ border="+${(pl:$((width-8))::-:)}+" ++ _zshell_put 4 2 5 "$border" ++ _zshell_put 4 $((height-5)) 5 "$border" ++ for (( y=3; y 1 )); then ++ _zshell_put $((sx+1)) $((sy+3)) 5 '|' ++ _zshell_put $((sx+6)) $((sy+3)) 5 '|' ++ fi ++ leg_y=$((sy+3+body_rows)) ++ if (( outfit == 2 )); then ++ if (( pose%2 )); then ++ _zshell_sprite $sx $leg_y 5 ' | |\ \ ' ' |_/_\_\' ++ else ++ _zshell_sprite $sx $leg_y 5 ' | || | ' ' |_||_| ' ++ fi ++ else ++ case $pose in ++ 0) _zshell_sprite $sx $leg_y 5 ' / \ ' ' _/ \_ ' ;; ++ 1) _zshell_sprite $sx $leg_y 5 ' > / ' ' / /_ ' ;; ++ 2) _zshell_sprite $sx $leg_y 5 ' / < ' ' /_ \_ ' ;; ++ 3) _zshell_sprite $sx $leg_y 5 ' \ \ ' ' _\ _\ ' ;; ++ esac ++ fi ++ # Arms animate around each silhouette, leaving hair and clothes stable. ++ if (( pose == 1 || pose == 3 )); then ++ _zshell_put $sx $sy 5 '\' ++ _zshell_put $((sx+1)) $((sy+1)) 5 '\' ++ _zshell_put $((sx+1)) $((sy+2)) 5 '|' ++ else ++ _zshell_put $((sx+1)) $((sy+3)) 5 '/' ++ _zshell_put $sx $((sy+4)) 5 '/' ++ fi ++ if (( pose == 1 || pose == 2 )); then ++ _zshell_put $((sx+7)) $sy 5 '/' ++ _zshell_put $((sx+6)) $((sy+1)) 5 '/' ++ _zshell_put $((sx+6)) $((sy+2)) 5 '|' ++ else ++ _zshell_put $((sx+6)) $((sy+3)) 5 '\' ++ _zshell_put $((sx+7)) $((sy+4)) 5 '\' ++ fi ++ done ++ _zshell_put 3 $height 0 'SCREENSAVER / PARTY' ++ _zshell_put $((width-21)) $height 0 'any key: after-party' ++ } ++ ++ _zshell_scene() { ++ integer y x i j base phase sway drift bob floor=$(( height - 5 )) ++ local leaf bubble ++ blank=${(pl:$width:: :)} ++ canvas=() inks=() ++ for (( y=1; y<=height; y++ )); do ++ canvas+=( "$blank" ) ++ inks+=( "${(pl:$width::0:)}" ) ++ done ++ if (( width < 48 || height < 18 )); then ++ if [[ $scene == aquarium ]]; then ++ _zshell_put 2 2 1 'A little more ocean, please.' ++ else ++ _zshell_put 2 2 1 'A little more room, please.' ++ fi ++ _zshell_put 2 4 0 'Resize to at least 49 x 18.' ++ _zshell_put 2 6 0 'Any key returns to your shell.' ++ return ++ fi ++ if [[ $scene == logo ]]; then ++ _zshell_logo ++ return ++ elif [[ $scene == hermit ]]; then ++ _zshell_hermit ++ return ++ elif [[ $scene == party ]]; then ++ _zshell_party ++ return ++ fi ++ ++ _zshell_put 3 2 1 'O H M Y Z S H' ++ _zshell_put $((width-17)) 2 0 'a shell aquarium' ++ _zshell_put 3 $height 0 'SCREENSAVER / AQUARIUM' ++ _zshell_put $((width-22)) $height 0 'any key: back to shore' ++ ++ # Tiny particles occupy the background; bubbles rise at different speeds. ++ for (( i=0; i 1 )) && leaf='(' ++ _zshell_put $((base + (sway>1))) $((floor+1-j)) 6 "$leaf" ++ done ++ done ++ ++ # Spirals ride a slow current. A triangle wave provides gentle vertical bob. ++ drift=$(( (tick / 9) % (width + 18) )) ++ x=$(( (width/4 + drift) % (width+18) - 9 )) ++ phase=$(( tick/12 % 6 )); bob=$(( phase < 3 ? phase : 5-phase )) ++ _zshell_sprite $x $((5+bob)) 2 ' __ ' ' /@/)' ' \_/' ++ ++ # Nautilus moves in the opposite direction, tentacles trailing behind it. ++ x=$(( (width*3/4 + width+20 - tick/6 % (width+20)) % (width+20) - 10 )) ++ _zshell_sprite $x $((5+(tick/18%2))) 2 ' .---. ' ' / (@) \ ' ' \ __/~~' ' `" ~~' ++ ++ # A fan shell closes briefly, then scoots during the same part of its cycle. ++ phase=$(( tick % 100 )) ++ drift=$(( (tick/100*4 + (phase>80 ? (phase-80)/5 : 0)) % (width+14) )) ++ x=$(( (width/2 + drift) % (width+14) - 7 )) ++ y=$(( floor-4 - (phase>80 && phase<95 ? 1 : 0) )) ++ if (( phase > 80 )); then ++ _zshell_sprite $x $y 4 ' _______ ' '(_______)' ' \/' ++ else ++ _zshell_sprite $x $y 4 ' .-----.' ' /|/|\|\' ' \|||||/' ' \___/' ++ fi ++ ++ # Conch and hermit crab live on different stretches of the seabed. ++ x=$(( 7 + (width/5 + tick/24) % (width-22) )) ++ _zshell_sprite $x $((floor-1)) 3 ' /\__' ' _/ / /\>' '(__/_/_)' ++ x=$(( 8 + (width*2/3 + tick/10) % (width-22) )) ++ if (( tick/5 % 2 )); then ++ _zshell_sprite $x $((floor-1)) 5 ' .-~-. ' ' ( ~ )oo' ' _/___/\\_' ++ else ++ _zshell_sprite $x $((floor-1)) 5 ' .-~-. ' ' ( ~ )oo' ' /_/_/ /\' ++ fi ++ } ++ ++ # Render color runs rather than individual cells. One write per frame and no ++ # per-frame subprocesses; the final column stays unused to prevent autowrap. ++ _zshell_render() { ++ integer row n ++ local text colors ink run ++ result=${terminfo[home]} ++ for (( row=1; row<=height; row++ )); do ++ text=${canvas[$row]} colors=${inks[$row]} ++ while [[ -n $colors ]]; do ++ ink=${colors[1]} ++ run=${colors%%[^$ink]*} ++ n=${#run} ++ result+="${palette[$((ink+1))]}${text[1,$n]}" ++ text=${text[$((n+1)),-1]} ++ colors=${colors[$((n+1)),-1]} ++ done ++ result+=${terminfo[el]} ++ (( row < height )) && result+=$'\r\n' ++ done ++ result+=${terminfo[sgr0]} ++ } ++ ++ if (( snapshot )); then ++ _zshell_scene ++ print -r -- "${(F)canvas}" ++ exit 0 ++ fi ++ if [[ ! -t 0 || ! -t 1 || -z $TERM || $TERM == dumb ]]; then ++ print -u2 -r -- 'omz shellsaver: run in an interactive terminal (or use --snapshot)' ++ exit 1 ++ fi ++ zmodload zsh/terminfo || exit 1 ++ zmodload zsh/datetime || exit 1 ++ local capability ++ for capability in smcup rmcup home clear civis cnorm sgr0 el; do ++ if [[ -z ${terminfo[$capability]} ]]; then ++ print -u2 -r -- "omz shellsaver: terminal lacks $capability; try --snapshot" ++ exit 1 ++ fi ++ done ++ ++ if (( mono || ${+NO_COLOR} || ${terminfo[colors]:-0} < 8 )); then ++ palette=( '' '' '' '' '' '' '' '' '' ) ++ elif (( ${terminfo[colors]} >= 256 )); then ++ palette=( $'\e[38;5;60m' $'\e[38;5;159m' $'\e[38;5;183m' ++ $'\e[38;5;222m' $'\e[38;5;210m' $'\e[38;5;230m' ++ $'\e[38;5;72m' $'\e[38;5;110m' $'\e[38;5;137m' ) ++ else ++ palette=( $'\e[34m' $'\e[36m' $'\e[35m' $'\e[33m' $'\e[31m' ++ $'\e[37m' $'\e[32m' $'\e[36m' $'\e[33m' ) ++ fi ++ ++ # Match the updater's exact truecolor and 256-color rainbow. The other ++ # scenes retain their own palettes, and monochrome always takes precedence. ++ if [[ $scene == logo ]] && (( !mono && !${+NO_COLOR} && ${terminfo[colors]:-0} >= 8 )); then ++ local -a rainbow ++ if [[ $COLORTERM == (truecolor|24bit) || $TERM == (iterm|tmux-truecolor|linux-truecolor|xterm-truecolor|screen-truecolor) ]]; then ++ rainbow=( $'\e[38;2;255;0;0m' $'\e[38;2;255;97;0m' $'\e[38;2;247;255;0m' ++ $'\e[38;2;0;255;30m' $'\e[38;2;77;0;255m' $'\e[38;2;168;0;255m' ++ $'\e[38;2;245;0;172m' ) ++ elif (( ${terminfo[colors]} >= 256 )); then ++ rainbow=( $'\e[38;5;196m' $'\e[38;5;202m' $'\e[38;5;226m' ++ $'\e[38;5;082m' $'\e[38;5;021m' $'\e[38;5;093m' $'\e[38;5;163m' ) ++ else ++ rainbow=( $'\e[31m' $'\e[33m' $'\e[33m' $'\e[32m' $'\e[34m' $'\e[35m' $'\e[35m' ) ++ fi ++ integer color_index ++ for (( color_index=1; color_index<=7; color_index++ )); do ++ palette[$((color_index+1))]=${rainbow[$color_index]} ++ done ++ fi ++ ++ _zshell_cleanup() { ++ # Ignore handled signals throughout restoration, including in child stty. ++ # Keep active set until both the screen and terminal modes are restored. ++ trap '' INT TERM HUP QUIT TSTP WINCH ++ (( active )) || return 0 ++ print -rn -- "${terminfo[sgr0]}${terminfo[cnorm]}${terminfo[rmcup]}" ++ command stty "$saved_tty" 2>/dev/null ++ active=0 ++ } ++ _zshell_size() { ++ local dimensions ++ integer old_width=$width old_height=$height first=$resized ++ dimensions=$(command stty size 2>/dev/null) || return 1 ++ local -a size=( ${=dimensions} ) ++ (( ${#size} == 2 && size[1] > 0 && size[2] > 1 )) || return 1 ++ height=$size[1] width=$((size[2]-1)) ++ # Very large terminals retain a calm, bounded scene in the top-left corner. ++ (( width > 180 )) && width=180 ++ (( height > 55 )) && height=55 ++ resized=0 ++ if (( first || old_width != width || old_height != height )); then ++ print -rn -- "${terminfo[clear]}" ++ fi ++ return 0 ++ } ++ ++ saved_tty=$(command stty -g) || exit 1 ++ trap '_zshell_cleanup' EXIT ++ trap 'exit 130' INT ++ trap 'exit 143' TERM ++ trap 'exit 129' HUP ++ trap 'exit 131' QUIT ++ # Suspending a raw terminal would strand the parent prompt. Exit on Ctrl-Z. ++ trap 'exit 148' TSTP ++ trap 'resized=1' WINCH ++ { ++ active=1 ++ command stty -echo -icanon -ixon min 1 time 0 || exit 1 ++ print -rn -- "${terminfo[smcup]}${terminfo[civis]}" ++ float started=$EPOCHREALTIME deadline wait_for next_size_check=0 ++ while true; do ++ # Zsh can defer WINCH while a timed read is active. Poll at 2 Hz as well. ++ if (( resized || EPOCHREALTIME >= next_size_check )); then ++ _zshell_size || exit 1 ++ next_size_check=$(( EPOCHREALTIME + 0.5 )) ++ fi ++ tick=$(( (EPOCHREALTIME-started)*10 )) ++ if (( seconds_limit && EPOCHREALTIME-started >= seconds_limit )); then break; fi ++ deadline=$(( EPOCHREALTIME + 0.1 )) ++ _zshell_scene ++ _zshell_render ++ print -rn -- "$result" ++ wait_for=$(( deadline-EPOCHREALTIME )) ++ (( wait_for < 0.005 )) && wait_for=0.005 ++ if read -r -k 1 -u 0 -t $wait_for key; then ++ # Drain the entire key sequence or paste until input goes quiet, so no ++ # queued suffix (including pasted commands) reaches the parent prompt. ++ while read -r -k 1 -u 0 -t 0.01 key; do :; done ++ break ++ fi ++ done ++ } always { ++ _zshell_cleanup ++ } ++ exit 0 ++} diff --git a/tasks/ohmyzsh__ohmyzsh-14167/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14167/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14167/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14167/task.toml b/tasks/ohmyzsh__ohmyzsh-14167/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bfdf23b0910806c6a2ef9bce1e64d28c9054dae4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14167/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14167" +description = "feat(cli): add Shellsavers terminal animations" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "9f9b28a13df35af968f0117cb142f0eba9cc6c41" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14167" +source_access = "auto" +built_at = "2026-11-16T16:09:56.865097+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:9c857883f52b0c9bfa0ade91fb3c118958ac81800a9762de765aa3b1583eb8cf" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-13T09:22:25Z" +diff_format = "unified" +context_files = [ + "README.md", + "lib/cli.zsh", + "tools/shellsaver.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 708 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.001324+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2960e1f582b1df0df587dd9e2f74f661b5cb80acfc2212df45ebd4d31fe87fb4" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14167/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14167/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14167/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14167/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14167/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..530dcd0f240f2015d15dc29529b4666e37000c53 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14167/tests/instruction.md @@ -0,0 +1,87 @@ +# Issue + +**Title:** feat(cli): add Shellsavers terminal animations + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +Shellsavers is a playful name for these on-demand terminal screensavers. + +Add `omz shellsaver [aquarium|logo|hermit|party]`. Running it without a scene opens the aquarium. The other scenes +show the updater's bouncing rainbow logo, a bewildered hermit crab, and a varied +dancing crowd. Any key returns to the shell. + +`omz shellsaver` appears in `omz help` and command completion, with completion for +scene names and options. `omz screensaver` remains a hidden alias. The main +README documents the commands, defaults, examples, and terminal requirements. +No plugin or configuration is needed; animation starts only when requested. +`omz shellsaver --list` lists all four scenes and marks the aquarium as the default, +without starting the animation or requiring an interactive terminal. +`--mono`/`NO_COLOR`, timed runs, and plain-text snapshots are supported. + +The renderer runs in a separate Zsh process, handles terminal resizing, and restores +terminal state on normal exit and handled signals. Runtime requirements are Zsh +5.8+, `stty`, and a compatible terminal. +The hidden `screensaver` alias delegates to `shellsaver`; it is not listed in help +or top-level command completion. + +## Demos: + +Recorded from the running Zsh renderer, with command labels added. + +### Aquarium demo + +https://github.com/user-attachments/assets/b2ec5bad-df71-4c66-a43f-f39d93ed271c + +### Rainbow logo demo + +https://github.com/user-attachments/assets/1afa4a29-7c67-460e-9fd0-c9259c554942 + +### Hermit demo + +https://github.com/user-attachments/assets/0843ff15-0305-4616-9cd3-4ea709392ae4 + +### Party demo + +https://github.com/user-attachments/assets/e9a08ebe-61c7-4b69-90f2-7ddb69e456d1 + +## Other comments: + +Developed with assistance from OpenAI Codex. + +Validation commands: + +```sh +zsh -n lib/cli.zsh +zsh -n tools/shellsaver.zsh +git diff --check +``` + +Validated locally on macOS with Zsh 5.9: all four scenes, native CLI dispatch, +terminal restoration, key/signal exits, resizing, monochrome output, and updater +rainbow colors. Linux, Zsh 5.8, and individual terminal applications still need a +compatibility pass before release. Development tests are kept outside this PR. + +This is a fun toy rather than a performance-tuned feature. While it runs, it uses roughly +15–30% of one CPU core at the largest window size. When it is not running, it costs +nothing: no startup work, no plugin, and no background process. + +Interactive Zsh completion was checked to advertise only `shellsaver`, while +completing all four scenes and options for both spellings. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9f9b28a13df3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14167/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14167/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..dfa1405533eba2f844fd022947ef16fa3f08a1d4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14167/tests/oracle.patch @@ -0,0 +1,763 @@ +diff --git a/README.md b/README.md +index ad507ecb..a443e1f1 100644 +--- a/README.md ++++ b/README.md +@@ -45,6 +45,7 @@ Twitter), and join us on [Discord](https://discord.gg/ohmyzsh). + - [Using Plugins](#using-plugins) + - [Themes](#themes) + - [Selecting A Theme](#selecting-a-theme) ++ - [Shellsavers](#shellsavers) + - [FAQ](#faq) + - [Advanced Topics](#advanced-topics) + - [Advanced Installation](#advanced-installation) +@@ -241,6 +242,33 @@ If you only know which themes you don't like, you can add them similarly to an i + ZSH_THEME_RANDOM_IGNORED=(pygmalion tjkirch_mod) + ``` + ++### Shellsavers ++ ++Give your terminal a little downtime with `omz shellsaver`—our playful name for ++terminal screensavers. The aquarium is the default; choose another scene to change the mood: ++ ++```zsh ++omz shellsaver # A quiet aquarium full of sea shells ++omz shellsaver logo # The updater's rainbow logo, bouncing around ++omz shellsaver hermit # A slightly lost hermit crab ++omz shellsaver party # A rainbow stage and a dancing crowd ++``` ++ ++Press any key or Ctrl-C to return to your shell. Screensavers run only when invoked ++and restore the terminal when they exit. No plugin or configuration change is needed. ++Use `omz help` to discover the command, and Tab to complete scene names and options. ++ ++```zsh ++omz shellsaver aquarium --seconds 30 # Stop automatically after 30 seconds ++omz shellsaver logo --mono # Use the terminal's foreground color ++omz shellsaver --list # List scenes (aquarium is the default) ++omz shellsaver --help # Show all scenes and options ++``` ++ ++Requires Zsh 5.8 or newer, `stty`, and an xterm-compatible terminal with alternate-screen ++support. No additional animation package is required. `NO_COLOR` is respected. ++A window of at least 49 columns by 18 rows is recommended. ++ + ### FAQ + + If you have some more questions or issues, you might find a solution in our +diff --git a/lib/cli.zsh b/lib/cli.zsh +index c713db5d..ed4af16e 100644 +--- a/lib/cli.zsh ++++ b/lib/cli.zsh +@@ -28,12 +28,25 @@ function _omz { + 'plugin:Manage plugins' + 'pr:Manage Oh My Zsh Pull Requests' + 'reload:Reload the current zsh session' ++ 'shellsaver:Launch a whimsical terminal screensaver' + 'shop:Open the Oh My Zsh shop' + 'theme:Manage themes' + 'update:Update Oh My Zsh' + 'version:Show the version' + ) + ++ if [[ "$words[2]" == (screensaver|shellsaver) ]] && (( CURRENT > 2 )); then ++ _arguments \ ++ '1:command:' \ ++ '2::scene:(aquarium logo hermit party)' \ ++ '--list[List available scenes]' \ ++ '--mono[Use the default foreground color]' \ ++ '--seconds[Exit after a number of seconds]:seconds:' \ ++ '--snapshot[Print a plain-text still]::frame:' \ ++ '--help[Show Shellsaver help]' ++ return ++ fi ++ + if (( CURRENT == 2 )); then + _describe 'command' cmds + elif (( CURRENT == 3 )); then +@@ -174,6 +187,7 @@ Available commands: + plugin Manage plugins + pr Manage Oh My Zsh Pull Requests + reload Reload the current zsh session ++ shellsaver [scene] Launch a Shellsaver (aquarium by default) + shop Open the Oh My Zsh shop + theme Manage themes + update Update Oh My Zsh +@@ -182,6 +196,15 @@ Available commands: + EOF + } + ++function _omz::shellsaver { ++ command zsh -f "$ZSH/tools/shellsaver.zsh" "$@" ++} ++ ++# Hidden alias; only shellsaver is advertised in help and command completion. ++function _omz::screensaver { ++ _omz::shellsaver "$@" ++} ++ + function _omz::changelog { + local version=${1:-HEAD} format=${3:-"--text"} + +diff --git a/tools/shellsaver.zsh b/tools/shellsaver.zsh +new file mode 100644 +index 00000000..4eb2c84b +--- /dev/null ++++ b/tools/shellsaver.zsh +@@ -0,0 +1,657 @@ ++#!/usr/bin/env zsh ++# Shared on-demand renderer for `omz shellsaver `. ++# The CLI launches a separate Zsh process, keeping all state out of the caller. ++{ ++ emulate -L zsh ++ setopt extendedglob ++ unsetopt multibyte ++ ++ integer tick=0 width=96 height=28 resized=1 active=0 seconds_limit=0 ++ integer mono=0 snapshot=0 scene_selected=0 ++ local saved_tty='' key='' blank='' result='' scene='' ++ local -a canvas inks palette ++ ++ _zshell_list() { ++ print -r -- 'aquarium Sea shells, a ~ hermit crab, and a quiet current (default). ++logo The Oh My Zsh wordmark takes a bouncing coffee break. ++hermit A bewildered hermit crab tries to find its working directory. ++party A rainbow terminal stage and a crowd of dancing shell fans.' ++ } ++ ++ _zshell_usage() { ++ print -r -- 'Oh My Zsh / experimental Shellsavers ++ ++Usage: omz shellsaver [aquarium|logo|hermit|party] [--mono] [--seconds N] ++ omz shellsaver [aquarium|logo|hermit|party] --snapshot [FRAME] ++ omz shellsaver --list ++' ++ _zshell_list ++ print -r -- ' ++Any key returns to the shell. Ctrl-C also exits safely. ++--list List available scenes and the default. ++--mono Use the terminal default foreground color. ++--seconds N Exit automatically after 1-3600 seconds. ++--snapshot Print a still at 96 columns x 28 rows (no terminal needed). ++ ++Requires Zsh 5.8+, stty, and an xterm-compatible terminal with an alternate screen. ++Nothing is installed or enabled automatically.' ++ } ++ case "${1-}" in ++ --help|-h) _zshell_usage; exit 0 ;; ++ ''|--*) scene=aquarium ;; ++ aquarium|logo|hermit|party) scene=$1; scene_selected=1; shift ;; ++ *) print -u2 -r -- "omz shellsaver: unknown scene: $1 (choose aquarium, logo, hermit, or party)"; exit 2 ;; ++ esac ++ ++ while (( $# )); do ++ case "$1" in ++ aquarium|logo|hermit|party) ++ if (( scene_selected )); then ++ print -u2 -r -- 'omz shellsaver: choose only one scene (try --help)' ++ exit 2 ++ fi ++ scene=$1; scene_selected=1 ;; ++ --help|-h) _zshell_usage; exit 0 ;; ++ --list) _zshell_list; exit 0 ;; ++ --mono) mono=1 ;; ++ --seconds) ++ shift ++ if [[ $1 != <1-3600> ]]; then ++ print -u2 -r -- 'omz shellsaver: --seconds requires an integer from 1 to 3600' ++ exit 2 ++ fi ++ seconds_limit=$1 ;; ++ --snapshot) ++ snapshot=1 ++ if [[ ${2-} == <0-100000> ]]; then tick=$2; shift; fi ;; ++ *) print -u2 -r -- "omz shellsaver: unknown argument: $1 (try --help)"; exit 2 ;; ++ esac ++ shift ++ done ++ ++ # Paint into separate ASCII text and color planes. Clip before slicing so a ++ # creature partly outside the viewport never wraps onto another terminal row. ++ _zshell_put() { ++ integer x=$1 y=$2 ink=$3 count skip ++ local text=$4 prefix='' suffix='' iprefix='' isuffix='' ++ (( y >= 1 && y <= height && x <= width )) || return 0 ++ if (( x < 1 )); then ++ skip=$(( 2 - x )) ++ (( skip <= ${#text} )) || return 0 ++ text=${text[$skip,-1]} ++ x=1 ++ fi ++ count=$(( width - x + 1 )) ++ text=${text[1,$count]} ++ count=${#text} ++ (( count )) || return 0 ++ if (( x > 1 )); then ++ prefix=${canvas[$y][1,$((x-1))]} ++ iprefix=${inks[$y][1,$((x-1))]} ++ fi ++ if (( x + count <= width )); then ++ suffix=${canvas[$y][$((x+count)),-1]} ++ isuffix=${inks[$y][$((x+count)),-1]} ++ fi ++ canvas[$y]="$prefix$text$suffix" ++ inks[$y]="$iprefix${(pl:$count::$ink:)}$isuffix" ++ } ++ ++ _zshell_sprite() { ++ integer sx=$1 sy=$2 color=$3 ++ shift 3 ++ local line ++ for line in "$@"; do ++ _zshell_put $sx $sy $color "$line" ++ (( sy++ )) ++ done ++ } ++ ++ _zshell_logo() { ++ # The full-size artwork and per-letter color bands match tools/upgrade.sh. ++ # A compact badge preserves the bounce in narrower terminal windows. ++ local -a logo logo_inks quips ++ local line glyph bands run ++ integer logo_width=0 logo_height span_x span_y px py x y color i j n offset ++ logo=( ++ ' __ __ ' ++ ' ____ / /_ ____ ___ __ __ ____ _____/ /_ ' ++ ' / __ \/ __ \ / __ `__ \/ / / / /_ / / ___/ __ \ ' ++ '/ /_/ / / / / / / / / / / /_/ / / /_(__ ) / / / ' ++ '\____/_/ /_/ /_/ /_/ /_/\__, / /___/____/_/ /_/ ' ++ ' /____/ ' ++ ) ++ logo_inks=( ++ 11111111122222222333333333334444444455555556666677777 ++ 11111111222222223333333333344444444555555566666777777 ++ 11111112222222233333333333444444445555555666666777777 ++ 11111112222222333333333333444444455555556666667777777 ++ 11111122222223333333333334444444555555556666677777777 ++ 11112222222233333333333444444445555555666667777777777 ++ ) ++ if (( width < 64 )); then ++ logo=( '.------------------.' '| Oh My Zsh |' '| ~ >_ |' "'------------------'" ) ++ logo_inks=() ++ for line in "${logo[@]}"; do ++ bands='' ++ for (( j=1; j<=${#line}; j++ )); do ++ bands+=$((1+(j-1)*7/${#line})) ++ done ++ logo_inks+=( "$bands" ) ++ done ++ fi ++ for line in "${logo[@]}"; do ++ (( ${#line} > logo_width )) && logo_width=${#line} ++ done ++ logo_height=${#logo} ++ span_x=$(( width-logo_width-4 )) ++ span_y=$(( height-logo_height-8 )) ++ px=$(( (tick/2+span_x/2) % (2*span_x) )) ++ py=$(( (tick/6+span_y/2) % (2*span_y) )) ++ x=$(( 3 + (px <= span_x ? px : 2*span_x-px) )) ++ y=$(( 5 + (py <= span_y ? py : 2*span_y-py) )) ++ ++ _zshell_put 3 2 1 'O H M Y Z S H' ++ _zshell_put $((width-17)) 2 0 'prompt on a break' ++ for (( i=0; i_' ++ if (( (px == 0 || px == span_x) && (py == 0 || py == span_y) )); then ++ _zshell_put $((x-2)) $((y-1)) 3 '*' ++ _zshell_put $((x+logo_width+1)) $((y-1)) 3 '*' ++ _zshell_put $(( (width-17)/2 )) $((height-2)) 3 'corner committed!' ++ else ++ quips=( 'home is where the ~ is' 'plugins on a coffee break' 'a delightful little detour' 'your prompt will be right back' ) ++ line=${quips[$((1+tick/80%${#quips}))]} ++ _zshell_put $(( (width-${#line})/2 )) $((height-2)) 0 "$line" ++ fi ++ _zshell_put 3 $height 0 'SCREENSAVER / LOGO' ++ _zshell_put $((width-21)) $height 0 'any key: back to work' ++ } ++ ++ _zshell_hermit() { ++ integer beat=$((tick/40%8)) within=$((tick%40)) shuffle=0 x y i ++ local left_eye='(o )' right_eye='(o )' mouth='._.' thought='...' legs ++ # Long, still looks make the tiny blinks and indecisive steps more visible. ++ case $beat in ++ 0) thought='...where was I going?' ;; ++ 1) left_eye='( o)'; right_eye='( o)'; thought='...over there?' ;; ++ 2) left_eye='(O )'; right_eye='( O)'; mouth=' o '; thought='pwd...?' ;; ++ 3) left_eye='( o)'; right_eye='(o )'; mouth='-_-'; thought='I brought home. Now what?' ;; ++ 4) left_eye='( o)'; right_eye='( o)'; shuffle=$((within/10)); thought='maybe this way.' ;; ++ 5) left_eye='( o)'; right_eye='(o )'; shuffle=3; thought='wrong directory.' ;; ++ 6) shuffle=$((3-within/10)); thought='cd .. ?' ;; ++ 7) left_eye='( ^)'; right_eye='(^ )'; mouth=' u '; thought='~ sweet ~ ...wait.' ;; ++ esac ++ # Short blinks run independently of the longer expression cycle. ++ if (( tick%73 >= 71 )); then left_eye='( -)'; right_eye='(- )'; fi ++ x=$(( (width-42)/2 + shuffle )) ++ y=$(( (height-12)/2 + 1 )) ++ _zshell_put 3 2 1 'O H M Y Z S H' ++ _zshell_put $((width-21)) 2 0 'a little shell-shocked' ++ # Photo-inspired three-quarter silhouette: tapered shell whorls behind ++ # the exposed head, unequal eyestalks, antennae and a hanging front claw. ++ _zshell_sprite $x $y 3 \ ++ ' __...---.' \ ++ " _.-' .--. '." \ ++ " .-' .' '. \\" \ ++ " .' _.-./ ~ \ |" \ ++ " / .' \ / |" \ ++ "/ / .-. |'-----' /" \ ++ '| ( ( @ ) / /' \ ++ "\ \ '-' .' .'" \ ++ " '-._'--'______.-'" ++ # Staggered eyes on stalks; the small head emerges from the shell opening. ++ _zshell_put $((x+25)) $((y+2)) 5 "$left_eye" ++ _zshell_put $((x+32)) $((y+1)) 5 "$right_eye" ++ _zshell_put $((x+27)) $((y+3)) 4 '|' ++ _zshell_put $((x+27)) $((y+4)) 4 '|' ++ _zshell_put $((x+33)) $((y+2)) 4 '/' ++ _zshell_put $((x+32)) $((y+3)) 4 '/' ++ _zshell_put $((x+31)) $((y+4)) 4 '/' ++ _zshell_put $((x+36)) $((y+3)) 5 "_.-'" ++ _zshell_put $((x+33)) $((y+4)) 5 ".-'" ++ _zshell_put $((x+32)) $((y+5)) 5 '/' ++ _zshell_put $((x+22)) $((y+5)) 4 '/___' ++ _zshell_put $((x+21)) $((y+6)) 4 '\___' ++ _zshell_put $((x+20)) $((y+7)) 4 '\__' ++ _zshell_put $((x+26)) $((y+5)) 4 '.----.' ++ _zshell_put $((x+25)) $((y+6)) 4 '/ \' ++ _zshell_put $((x+23)) $((y+7)) 4 '__\______/' ++ _zshell_put $((x+21)) $((y+8)) 4 '\___/ /\ \__' ++ _zshell_put $((x+27)) $((y+6)) 5 "$mouth" ++ # Legs bend down and forward instead of spreading symmetrically sideways. ++ _zshell_put $((x+18)) $((y+9)) 4 '\___/ / \___' ++ _zshell_put $((x+16)) $((y+10)) 4 '___/ / \' ++ legs=' _/____/ \_' ++ if (( (beat == 4 || beat == 6) && within/3%2 )); then ++ legs=' /___/ _/' ++ fi ++ _zshell_put $x $((y+11)) 4 "$legs" ++ # The big claw hangs in front. The much smaller claw tucks under the face. ++ if (( beat == 3 )); then ++ _zshell_sprite $((x+35)) $((y+7)) 4 ' __ ' '/ \' '| / |' ' V V ' ++ _zshell_put $((x+32)) $((y+6)) 4 '()' ++ else ++ _zshell_sprite $((x+35)) $((y+8)) 4 ' __ ' '/ \' '| / |' ' V V ' ++ _zshell_put $((x+30)) $((y+8)) 4 '()' ++ fi ++ if (( beat == 2 || beat == 5 )); then ++ _zshell_put $((x+39)) $y 1 '?' ++ fi ++ if (( height >= 24 )); then ++ for (( i=3; i= 120 )); then ++ scale=2 ++ fi ++ letters=( O H M Y Z S H ) ++ letter_colors=( 4 3 6 1 7 2 4 ) ++ logo_width=$(( (7*glyph_width+6+4)*scale )) ++ logo_x=$(( (width-logo_width)/2+1 )) ++ logo_y=$(( height/4 )); (( logo_y < 4 )) && logo_y=4 ++ ++ # A terminal window behind the crowd, including tiny window controls. ++ border="+${(pl:$((width-8))::-:)}+" ++ _zshell_put 4 2 5 "$border" ++ _zshell_put 4 $((height-5)) 5 "$border" ++ for (( y=3; y 1 )); then ++ _zshell_put $((sx+1)) $((sy+3)) 5 '|' ++ _zshell_put $((sx+6)) $((sy+3)) 5 '|' ++ fi ++ leg_y=$((sy+3+body_rows)) ++ if (( outfit == 2 )); then ++ if (( pose%2 )); then ++ _zshell_sprite $sx $leg_y 5 ' | |\ \ ' ' |_/_\_\' ++ else ++ _zshell_sprite $sx $leg_y 5 ' | || | ' ' |_||_| ' ++ fi ++ else ++ case $pose in ++ 0) _zshell_sprite $sx $leg_y 5 ' / \ ' ' _/ \_ ' ;; ++ 1) _zshell_sprite $sx $leg_y 5 ' > / ' ' / /_ ' ;; ++ 2) _zshell_sprite $sx $leg_y 5 ' / < ' ' /_ \_ ' ;; ++ 3) _zshell_sprite $sx $leg_y 5 ' \ \ ' ' _\ _\ ' ;; ++ esac ++ fi ++ # Arms animate around each silhouette, leaving hair and clothes stable. ++ if (( pose == 1 || pose == 3 )); then ++ _zshell_put $sx $sy 5 '\' ++ _zshell_put $((sx+1)) $((sy+1)) 5 '\' ++ _zshell_put $((sx+1)) $((sy+2)) 5 '|' ++ else ++ _zshell_put $((sx+1)) $((sy+3)) 5 '/' ++ _zshell_put $sx $((sy+4)) 5 '/' ++ fi ++ if (( pose == 1 || pose == 2 )); then ++ _zshell_put $((sx+7)) $sy 5 '/' ++ _zshell_put $((sx+6)) $((sy+1)) 5 '/' ++ _zshell_put $((sx+6)) $((sy+2)) 5 '|' ++ else ++ _zshell_put $((sx+6)) $((sy+3)) 5 '\' ++ _zshell_put $((sx+7)) $((sy+4)) 5 '\' ++ fi ++ done ++ _zshell_put 3 $height 0 'SCREENSAVER / PARTY' ++ _zshell_put $((width-21)) $height 0 'any key: after-party' ++ } ++ ++ _zshell_scene() { ++ integer y x i j base phase sway drift bob floor=$(( height - 5 )) ++ local leaf bubble ++ blank=${(pl:$width:: :)} ++ canvas=() inks=() ++ for (( y=1; y<=height; y++ )); do ++ canvas+=( "$blank" ) ++ inks+=( "${(pl:$width::0:)}" ) ++ done ++ if (( width < 48 || height < 18 )); then ++ if [[ $scene == aquarium ]]; then ++ _zshell_put 2 2 1 'A little more ocean, please.' ++ else ++ _zshell_put 2 2 1 'A little more room, please.' ++ fi ++ _zshell_put 2 4 0 'Resize to at least 49 x 18.' ++ _zshell_put 2 6 0 'Any key returns to your shell.' ++ return ++ fi ++ if [[ $scene == logo ]]; then ++ _zshell_logo ++ return ++ elif [[ $scene == hermit ]]; then ++ _zshell_hermit ++ return ++ elif [[ $scene == party ]]; then ++ _zshell_party ++ return ++ fi ++ ++ _zshell_put 3 2 1 'O H M Y Z S H' ++ _zshell_put $((width-17)) 2 0 'a shell aquarium' ++ _zshell_put 3 $height 0 'SCREENSAVER / AQUARIUM' ++ _zshell_put $((width-22)) $height 0 'any key: back to shore' ++ ++ # Tiny particles occupy the background; bubbles rise at different speeds. ++ for (( i=0; i 1 )) && leaf='(' ++ _zshell_put $((base + (sway>1))) $((floor+1-j)) 6 "$leaf" ++ done ++ done ++ ++ # Spirals ride a slow current. A triangle wave provides gentle vertical bob. ++ drift=$(( (tick / 9) % (width + 18) )) ++ x=$(( (width/4 + drift) % (width+18) - 9 )) ++ phase=$(( tick/12 % 6 )); bob=$(( phase < 3 ? phase : 5-phase )) ++ _zshell_sprite $x $((5+bob)) 2 ' __ ' ' /@/)' ' \_/' ++ ++ # Nautilus moves in the opposite direction, tentacles trailing behind it. ++ x=$(( (width*3/4 + width+20 - tick/6 % (width+20)) % (width+20) - 10 )) ++ _zshell_sprite $x $((5+(tick/18%2))) 2 ' .---. ' ' / (@) \ ' ' \ __/~~' ' `" ~~' ++ ++ # A fan shell closes briefly, then scoots during the same part of its cycle. ++ phase=$(( tick % 100 )) ++ drift=$(( (tick/100*4 + (phase>80 ? (phase-80)/5 : 0)) % (width+14) )) ++ x=$(( (width/2 + drift) % (width+14) - 7 )) ++ y=$(( floor-4 - (phase>80 && phase<95 ? 1 : 0) )) ++ if (( phase > 80 )); then ++ _zshell_sprite $x $y 4 ' _______ ' '(_______)' ' \/' ++ else ++ _zshell_sprite $x $y 4 ' .-----.' ' /|/|\|\' ' \|||||/' ' \___/' ++ fi ++ ++ # Conch and hermit crab live on different stretches of the seabed. ++ x=$(( 7 + (width/5 + tick/24) % (width-22) )) ++ _zshell_sprite $x $((floor-1)) 3 ' /\__' ' _/ / /\>' '(__/_/_)' ++ x=$(( 8 + (width*2/3 + tick/10) % (width-22) )) ++ if (( tick/5 % 2 )); then ++ _zshell_sprite $x $((floor-1)) 5 ' .-~-. ' ' ( ~ )oo' ' _/___/\\_' ++ else ++ _zshell_sprite $x $((floor-1)) 5 ' .-~-. ' ' ( ~ )oo' ' /_/_/ /\' ++ fi ++ } ++ ++ # Render color runs rather than individual cells. One write per frame and no ++ # per-frame subprocesses; the final column stays unused to prevent autowrap. ++ _zshell_render() { ++ integer row n ++ local text colors ink run ++ result=${terminfo[home]} ++ for (( row=1; row<=height; row++ )); do ++ text=${canvas[$row]} colors=${inks[$row]} ++ while [[ -n $colors ]]; do ++ ink=${colors[1]} ++ run=${colors%%[^$ink]*} ++ n=${#run} ++ result+="${palette[$((ink+1))]}${text[1,$n]}" ++ text=${text[$((n+1)),-1]} ++ colors=${colors[$((n+1)),-1]} ++ done ++ result+=${terminfo[el]} ++ (( row < height )) && result+=$'\r\n' ++ done ++ result+=${terminfo[sgr0]} ++ } ++ ++ if (( snapshot )); then ++ _zshell_scene ++ print -r -- "${(F)canvas}" ++ exit 0 ++ fi ++ if [[ ! -t 0 || ! -t 1 || -z $TERM || $TERM == dumb ]]; then ++ print -u2 -r -- 'omz shellsaver: run in an interactive terminal (or use --snapshot)' ++ exit 1 ++ fi ++ zmodload zsh/terminfo || exit 1 ++ zmodload zsh/datetime || exit 1 ++ local capability ++ for capability in smcup rmcup home clear civis cnorm sgr0 el; do ++ if [[ -z ${terminfo[$capability]} ]]; then ++ print -u2 -r -- "omz shellsaver: terminal lacks $capability; try --snapshot" ++ exit 1 ++ fi ++ done ++ ++ if (( mono || ${+NO_COLOR} || ${terminfo[colors]:-0} < 8 )); then ++ palette=( '' '' '' '' '' '' '' '' '' ) ++ elif (( ${terminfo[colors]} >= 256 )); then ++ palette=( $'\e[38;5;60m' $'\e[38;5;159m' $'\e[38;5;183m' ++ $'\e[38;5;222m' $'\e[38;5;210m' $'\e[38;5;230m' ++ $'\e[38;5;72m' $'\e[38;5;110m' $'\e[38;5;137m' ) ++ else ++ palette=( $'\e[34m' $'\e[36m' $'\e[35m' $'\e[33m' $'\e[31m' ++ $'\e[37m' $'\e[32m' $'\e[36m' $'\e[33m' ) ++ fi ++ ++ # Match the updater's exact truecolor and 256-color rainbow. The other ++ # scenes retain their own palettes, and monochrome always takes precedence. ++ if [[ $scene == logo ]] && (( !mono && !${+NO_COLOR} && ${terminfo[colors]:-0} >= 8 )); then ++ local -a rainbow ++ if [[ $COLORTERM == (truecolor|24bit) || $TERM == (iterm|tmux-truecolor|linux-truecolor|xterm-truecolor|screen-truecolor) ]]; then ++ rainbow=( $'\e[38;2;255;0;0m' $'\e[38;2;255;97;0m' $'\e[38;2;247;255;0m' ++ $'\e[38;2;0;255;30m' $'\e[38;2;77;0;255m' $'\e[38;2;168;0;255m' ++ $'\e[38;2;245;0;172m' ) ++ elif (( ${terminfo[colors]} >= 256 )); then ++ rainbow=( $'\e[38;5;196m' $'\e[38;5;202m' $'\e[38;5;226m' ++ $'\e[38;5;082m' $'\e[38;5;021m' $'\e[38;5;093m' $'\e[38;5;163m' ) ++ else ++ rainbow=( $'\e[31m' $'\e[33m' $'\e[33m' $'\e[32m' $'\e[34m' $'\e[35m' $'\e[35m' ) ++ fi ++ integer color_index ++ for (( color_index=1; color_index<=7; color_index++ )); do ++ palette[$((color_index+1))]=${rainbow[$color_index]} ++ done ++ fi ++ ++ _zshell_cleanup() { ++ # Ignore handled signals throughout restoration, including in child stty. ++ # Keep active set until both the screen and terminal modes are restored. ++ trap '' INT TERM HUP QUIT TSTP WINCH ++ (( active )) || return 0 ++ print -rn -- "${terminfo[sgr0]}${terminfo[cnorm]}${terminfo[rmcup]}" ++ command stty "$saved_tty" 2>/dev/null ++ active=0 ++ } ++ _zshell_size() { ++ local dimensions ++ integer old_width=$width old_height=$height first=$resized ++ dimensions=$(command stty size 2>/dev/null) || return 1 ++ local -a size=( ${=dimensions} ) ++ (( ${#size} == 2 && size[1] > 0 && size[2] > 1 )) || return 1 ++ height=$size[1] width=$((size[2]-1)) ++ # Very large terminals retain a calm, bounded scene in the top-left corner. ++ (( width > 180 )) && width=180 ++ (( height > 55 )) && height=55 ++ resized=0 ++ if (( first || old_width != width || old_height != height )); then ++ print -rn -- "${terminfo[clear]}" ++ fi ++ return 0 ++ } ++ ++ saved_tty=$(command stty -g) || exit 1 ++ trap '_zshell_cleanup' EXIT ++ trap 'exit 130' INT ++ trap 'exit 143' TERM ++ trap 'exit 129' HUP ++ trap 'exit 131' QUIT ++ # Suspending a raw terminal would strand the parent prompt. Exit on Ctrl-Z. ++ trap 'exit 148' TSTP ++ trap 'resized=1' WINCH ++ { ++ active=1 ++ command stty -echo -icanon -ixon min 1 time 0 || exit 1 ++ print -rn -- "${terminfo[smcup]}${terminfo[civis]}" ++ float started=$EPOCHREALTIME deadline wait_for next_size_check=0 ++ while true; do ++ # Zsh can defer WINCH while a timed read is active. Poll at 2 Hz as well. ++ if (( resized || EPOCHREALTIME >= next_size_check )); then ++ _zshell_size || exit 1 ++ next_size_check=$(( EPOCHREALTIME + 0.5 )) ++ fi ++ tick=$(( (EPOCHREALTIME-started)*10 )) ++ if (( seconds_limit && EPOCHREALTIME-started >= seconds_limit )); then break; fi ++ deadline=$(( EPOCHREALTIME + 0.1 )) ++ _zshell_scene ++ _zshell_render ++ print -rn -- "$result" ++ wait_for=$(( deadline-EPOCHREALTIME )) ++ (( wait_for < 0.005 )) && wait_for=0.005 ++ if read -r -k 1 -u 0 -t $wait_for key; then ++ # Drain the entire key sequence or paste until input goes quiet, so no ++ # queued suffix (including pasted commands) reaches the parent prompt. ++ while read -r -k 1 -u 0 -t 0.01 key; do :; done ++ break ++ fi ++ done ++ } always { ++ _zshell_cleanup ++ } ++ exit 0 ++} diff --git a/tasks/ohmyzsh__ohmyzsh-14167/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14167/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9dd23e396a7cbec6da12adae9a706a5794f0c6c0 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14167/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 9f9b28a13df35af968f0117cb142f0eba9cc6c41 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14167/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14167/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14167/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14171/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14171/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2d2f160ca86e5c7741142ee793ed3fb408634c90 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14171/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 42a4ccb1b14dbeffe81259105a5243b4f4cb618e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 42a4ccb1b14dbeffe81259105a5243b4f4cb618e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 42a4ccb1b14dbeffe81259105a5243b4f4cb618e \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14171/instruction.md b/tasks/ohmyzsh__ohmyzsh-14171/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..33f90bfca9835cf6a166afb63e1e0873bd6a0591 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14171/instruction.md @@ -0,0 +1,57 @@ +# Issue + +**Title:** feat(gpg-agent): add `ssh-support` style to skip the gpgconf check + +## Description + +_Drafted with Claude_ + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Add an `ssh-support` style to the `gpg-agent` plugin. With `no` the plugin sets `GPG_TTY` and stops. With `yes` it sets `SSH_AUTH_SOCK` without checking. Left unset, it detects `enable-ssh-support` exactly as it does today. +- Document the style in the plugin's README, and update the README's summary of when `SSH_AUTH_SOCK` is set. +- Wrap the detection line, which was 115 characters, to fit the style guide's 80. + +## Other comments: + +**The problem.** The plugin runs `gpgconf --list-options gpg-agent` on every shell start, to learn whether `enable-ssh-support` is set. On my machine that one command takes about 600 ms (macOS on Apple silicon, GnuPG 2.5.24 from Homebrew, median of five runs). A new shell took about 2.2 seconds in total, and this was the second largest item. I do not use gpg-agent for ssh, so the answer is always no. + +**What `no` skips.** Besides the check, it skips the preexec hook that runs `gpg-connect-agent updatestartuptty /bye` before every command. The GnuPG manual describes that command under `--enable-ssh-support`, as the way to point the agent at the current tty for ssh. It has no job when ssh support is off, and it costs about 19 ms per command here. + +**Default behavior does not change.** With the style unset the plugin takes the same path as before. I ran the old and new plugin files side by side, with the real `gpgconf` and with a stub reporting ssh support on and off. The hook, `SSH_AUTH_SOCK` and `SSH_AGENT_PID` came out the same in all three cases. + +| `ssh-support` | `gpgconf` check | Time to load the plugin | +| --- | --- | --- | +| unset | runs | about 680 ms | +| `yes` | skipped | about 35 ms | +| `no` | skipped | under 1 ms | + +I have only measured this on macOS. I would be glad to hear whether the check is as slow elsewhere. + +**Alternatives I considered,** from least to most appealing: + +- Drop the plugin and put `export GPG_TTY=$TTY` in my own zshrc. That is what the plugin amounts to for anyone without ssh support, but it helps nobody else. +- Cache the result of the check between shells. That needs invalidation whenever the configuration changes. +- Read `gpg-agent.conf` directly. It is fast, but it misses an option set in a system-wide configuration file, so it is not equivalent to asking `gpgconf`. + +A style keeps the detection authoritative and lets a user who already knows the answer skip it. + +**Related.** I found no open issue or pull request about this. #13287 proposed a different change to this plugin and was closed because it altered the default behavior for everyone. This one leaves the default alone. Nothing changes unless the style is set. + +**AI disclosure.** I used Claude Code to profile my shell startup, write this patch and draft this description. I have reviewed the change and can explain it. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `42a4ccb1b14d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14171/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14171/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..92d13d631642806d47bc018ed74d5e7af8830ce4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14171/solution/patch.diff @@ -0,0 +1,82 @@ +diff --git a/plugins/gpg-agent/README.md b/plugins/gpg-agent/README.md +index d66c37a5..cfabc4c7 100644 +--- a/plugins/gpg-agent/README.md ++++ b/plugins/gpg-agent/README.md +@@ -5,10 +5,40 @@ Applies some fixes for some common issues encountered with [GPG's gpg-agent](htt + More specifically, this plugin: + + - Updates the `GPG_TTY` environment variable before each shell execution. +-- Updates the `SSH_AUTH_SOCK` environment variable if `enable-ssh-support` is turned on. ++- Updates the `SSH_AUTH_SOCK` environment variable if `gpg-agent` is your SSH ++ agent. By default the plugin checks whether `enable-ssh-support` is turned ++ on. The [`ssh-support` setting](#settings) lets you say so yourself. + + To use it, add `gpg-agent` to the plugins array of your zshrc file: + + ```zsh + plugins=(... gpg-agent) + ``` ++ ++## Settings ++ ++Every time a shell starts, the plugin runs `gpgconf --list-options gpg-agent` to ++find out whether `enable-ssh-support` is turned on. That check can be slow. If ++you already know the answer, state it with the `ssh-support` style and the ++plugin skips the check. Set it in your zshrc, before Oh My Zsh is sourced. ++ ++If you don't use `gpg-agent` as your SSH agent: ++ ++```zsh ++zstyle ':omz:plugins:gpg-agent' ssh-support no ++``` ++ ++The plugin then only sets `GPG_TTY`. It leaves `SSH_AUTH_SOCK` alone, and it ++doesn't update the agent's tty before each command, which only SSH support ++needs. ++ ++If you do use `gpg-agent` as your SSH agent: ++ ++```zsh ++zstyle ':omz:plugins:gpg-agent' ssh-support yes ++``` ++ ++The plugin then sets `SSH_AUTH_SOCK` without checking. `enable-ssh-support` ++still has to be set in your `gpg-agent.conf` for SSH to work. ++ ++Leave the style unset to keep the automatic check. +diff --git a/plugins/gpg-agent/gpg-agent.plugin.zsh b/plugins/gpg-agent/gpg-agent.plugin.zsh +index 1f4be20b..47595cbf 100644 +--- a/plugins/gpg-agent/gpg-agent.plugin.zsh ++++ b/plugins/gpg-agent/gpg-agent.plugin.zsh +@@ -1,5 +1,16 @@ + export GPG_TTY=$TTY + ++# The ssh-support style says whether gpg-agent is used as the ssh agent. ++# Setting it saves asking gpgconf, which can be slow. ++zstyle -t ':omz:plugins:gpg-agent' ssh-support ++_gpg_agent_ssh_support=$? # 0 if yes, 1 if no, 2 if not set ++ ++# Everything below is only needed for ssh support ++if (( _gpg_agent_ssh_support == 1 )); then ++ unset _gpg_agent_ssh_support ++ return ++fi ++ + # Fix for passphrase prompt on the correct tty + # See https://www.gnupg.org/documentation/manuals/gnupg/Agent-Options.html#option-_002d_002denable_002dssh_002dsupport + function _gpg-agent_update-tty_preexec { +@@ -9,9 +20,13 @@ autoload -U add-zsh-hook + add-zsh-hook preexec _gpg-agent_update-tty_preexec + + # If enable-ssh-support is set, fix ssh agent integration +-if [[ $(gpgconf --list-options gpg-agent 2>/dev/null | awk -F: '$1=="enable-ssh-support" {print $10}') = 1 ]]; then ++if (( _gpg_agent_ssh_support == 0 )) \ ++ || [[ $(gpgconf --list-options gpg-agent 2>/dev/null \ ++ | awk -F: '$1=="enable-ssh-support" {print $10}') = 1 ]]; then + unset SSH_AGENT_PID + if [[ "${gnupg_SSH_AUTH_SOCK_by:-0}" -ne $$ ]]; then + export SSH_AUTH_SOCK="$(gpgconf --list-dirs agent-ssh-socket)" + fi + fi ++ ++unset _gpg_agent_ssh_support diff --git a/tasks/ohmyzsh__ohmyzsh-14171/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14171/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14171/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14171/task.toml b/tasks/ohmyzsh__ohmyzsh-14171/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..54e3d619f6800f14f3b2a87dd341ef3df90d8d3a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14171/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14171" +description = "feat(gpg-agent): add `ssh-support` style to skip the gpgconf check" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "42a4ccb1b14dbeffe81259105a5243b4f4cb618e" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14171" +source_access = "auto" +built_at = "2026-11-16T16:09:56.879099+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:206fc90fa911772ad92c86df72ccb381469840a9bc00ca8ae658c947e6eec979" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-11T22:46:27Z" +diff_format = "unified" +context_files = [ + "plugins/gpg-agent/README.md", + "plugins/gpg-agent/gpg-agent.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 49 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.001955+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d7de01c73d23027acb94bdaa200f519da3f5f6e033582e108635ce56b8dcc4ee" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14171/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14171/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14171/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14171/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14171/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..33f90bfca9835cf6a166afb63e1e0873bd6a0591 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14171/tests/instruction.md @@ -0,0 +1,57 @@ +# Issue + +**Title:** feat(gpg-agent): add `ssh-support` style to skip the gpgconf check + +## Description + +_Drafted with Claude_ + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Add an `ssh-support` style to the `gpg-agent` plugin. With `no` the plugin sets `GPG_TTY` and stops. With `yes` it sets `SSH_AUTH_SOCK` without checking. Left unset, it detects `enable-ssh-support` exactly as it does today. +- Document the style in the plugin's README, and update the README's summary of when `SSH_AUTH_SOCK` is set. +- Wrap the detection line, which was 115 characters, to fit the style guide's 80. + +## Other comments: + +**The problem.** The plugin runs `gpgconf --list-options gpg-agent` on every shell start, to learn whether `enable-ssh-support` is set. On my machine that one command takes about 600 ms (macOS on Apple silicon, GnuPG 2.5.24 from Homebrew, median of five runs). A new shell took about 2.2 seconds in total, and this was the second largest item. I do not use gpg-agent for ssh, so the answer is always no. + +**What `no` skips.** Besides the check, it skips the preexec hook that runs `gpg-connect-agent updatestartuptty /bye` before every command. The GnuPG manual describes that command under `--enable-ssh-support`, as the way to point the agent at the current tty for ssh. It has no job when ssh support is off, and it costs about 19 ms per command here. + +**Default behavior does not change.** With the style unset the plugin takes the same path as before. I ran the old and new plugin files side by side, with the real `gpgconf` and with a stub reporting ssh support on and off. The hook, `SSH_AUTH_SOCK` and `SSH_AGENT_PID` came out the same in all three cases. + +| `ssh-support` | `gpgconf` check | Time to load the plugin | +| --- | --- | --- | +| unset | runs | about 680 ms | +| `yes` | skipped | about 35 ms | +| `no` | skipped | under 1 ms | + +I have only measured this on macOS. I would be glad to hear whether the check is as slow elsewhere. + +**Alternatives I considered,** from least to most appealing: + +- Drop the plugin and put `export GPG_TTY=$TTY` in my own zshrc. That is what the plugin amounts to for anyone without ssh support, but it helps nobody else. +- Cache the result of the check between shells. That needs invalidation whenever the configuration changes. +- Read `gpg-agent.conf` directly. It is fast, but it misses an option set in a system-wide configuration file, so it is not equivalent to asking `gpgconf`. + +A style keeps the detection authoritative and lets a user who already knows the answer skip it. + +**Related.** I found no open issue or pull request about this. #13287 proposed a different change to this plugin and was closed because it altered the default behavior for everyone. This one leaves the default alone. Nothing changes unless the style is set. + +**AI disclosure.** I used Claude Code to profile my shell startup, write this patch and draft this description. I have reviewed the change and can explain it. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `42a4ccb1b14d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14171/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14171/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..92d13d631642806d47bc018ed74d5e7af8830ce4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14171/tests/oracle.patch @@ -0,0 +1,82 @@ +diff --git a/plugins/gpg-agent/README.md b/plugins/gpg-agent/README.md +index d66c37a5..cfabc4c7 100644 +--- a/plugins/gpg-agent/README.md ++++ b/plugins/gpg-agent/README.md +@@ -5,10 +5,40 @@ Applies some fixes for some common issues encountered with [GPG's gpg-agent](htt + More specifically, this plugin: + + - Updates the `GPG_TTY` environment variable before each shell execution. +-- Updates the `SSH_AUTH_SOCK` environment variable if `enable-ssh-support` is turned on. ++- Updates the `SSH_AUTH_SOCK` environment variable if `gpg-agent` is your SSH ++ agent. By default the plugin checks whether `enable-ssh-support` is turned ++ on. The [`ssh-support` setting](#settings) lets you say so yourself. + + To use it, add `gpg-agent` to the plugins array of your zshrc file: + + ```zsh + plugins=(... gpg-agent) + ``` ++ ++## Settings ++ ++Every time a shell starts, the plugin runs `gpgconf --list-options gpg-agent` to ++find out whether `enable-ssh-support` is turned on. That check can be slow. If ++you already know the answer, state it with the `ssh-support` style and the ++plugin skips the check. Set it in your zshrc, before Oh My Zsh is sourced. ++ ++If you don't use `gpg-agent` as your SSH agent: ++ ++```zsh ++zstyle ':omz:plugins:gpg-agent' ssh-support no ++``` ++ ++The plugin then only sets `GPG_TTY`. It leaves `SSH_AUTH_SOCK` alone, and it ++doesn't update the agent's tty before each command, which only SSH support ++needs. ++ ++If you do use `gpg-agent` as your SSH agent: ++ ++```zsh ++zstyle ':omz:plugins:gpg-agent' ssh-support yes ++``` ++ ++The plugin then sets `SSH_AUTH_SOCK` without checking. `enable-ssh-support` ++still has to be set in your `gpg-agent.conf` for SSH to work. ++ ++Leave the style unset to keep the automatic check. +diff --git a/plugins/gpg-agent/gpg-agent.plugin.zsh b/plugins/gpg-agent/gpg-agent.plugin.zsh +index 1f4be20b..47595cbf 100644 +--- a/plugins/gpg-agent/gpg-agent.plugin.zsh ++++ b/plugins/gpg-agent/gpg-agent.plugin.zsh +@@ -1,5 +1,16 @@ + export GPG_TTY=$TTY + ++# The ssh-support style says whether gpg-agent is used as the ssh agent. ++# Setting it saves asking gpgconf, which can be slow. ++zstyle -t ':omz:plugins:gpg-agent' ssh-support ++_gpg_agent_ssh_support=$? # 0 if yes, 1 if no, 2 if not set ++ ++# Everything below is only needed for ssh support ++if (( _gpg_agent_ssh_support == 1 )); then ++ unset _gpg_agent_ssh_support ++ return ++fi ++ + # Fix for passphrase prompt on the correct tty + # See https://www.gnupg.org/documentation/manuals/gnupg/Agent-Options.html#option-_002d_002denable_002dssh_002dsupport + function _gpg-agent_update-tty_preexec { +@@ -9,9 +20,13 @@ autoload -U add-zsh-hook + add-zsh-hook preexec _gpg-agent_update-tty_preexec + + # If enable-ssh-support is set, fix ssh agent integration +-if [[ $(gpgconf --list-options gpg-agent 2>/dev/null | awk -F: '$1=="enable-ssh-support" {print $10}') = 1 ]]; then ++if (( _gpg_agent_ssh_support == 0 )) \ ++ || [[ $(gpgconf --list-options gpg-agent 2>/dev/null \ ++ | awk -F: '$1=="enable-ssh-support" {print $10}') = 1 ]]; then + unset SSH_AGENT_PID + if [[ "${gnupg_SSH_AUTH_SOCK_by:-0}" -ne $$ ]]; then + export SSH_AUTH_SOCK="$(gpgconf --list-dirs agent-ssh-socket)" + fi + fi ++ ++unset _gpg_agent_ssh_support diff --git a/tasks/ohmyzsh__ohmyzsh-14171/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14171/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..20632ad7ccb7ec595d82e801c12cae199089c12c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14171/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 42a4ccb1b14dbeffe81259105a5243b4f4cb618e > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14171/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14171/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14171/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14172/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14172/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1a293a996bf2fa33fe3901a7cddc09e021469bf4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14172/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 083c339e0622bfc144b66ebf1a2e8dbe7d2ada0d 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 083c339e0622bfc144b66ebf1a2e8dbe7d2ada0d \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 083c339e0622bfc144b66ebf1a2e8dbe7d2ada0d \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14172/instruction.md b/tasks/ohmyzsh__ohmyzsh-14172/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d8860d1a5fe0376b1c33101f4034f148e02c4da1 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14172/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** fix(termsupport): improve Apple Terminal support + +## Description + +## Standards checklist: + + + +- [X] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [X] The code follows the code style guide detailed in the wiki. +- [X] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [X] The code is efficient, to the best of my ability, and does not waste computer resources. +- [X] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- `nsterm` is the "correct" `$TERM` for Apple's Terminal.app, so add it to the list of good terminal emulators. +- Apple's Terminal.app uses the same window/tab title sequences as iTerm.app (status line columns 2 and 1, respectively), so give it the same treatment as iTerm for window title. + +## Other comments: + +This patch was written in 2022, and I rebased it today to submit as PR. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `083c339e0622`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14172/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14172/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..3d8393d3a25436a7a4782aaac579999d7c63d876 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14172/solution/patch.diff @@ -0,0 +1,46 @@ +diff --git a/lib/termsupport.zsh b/lib/termsupport.zsh +index 6af8fe73..c2623887 100644 +--- a/lib/termsupport.zsh ++++ b/lib/termsupport.zsh +@@ -5,7 +5,6 @@ + # See: http://www.faqs.org/docs/Linux-mini/Xterm-Title.html#ss3.1 + # Fully supports screen, iterm, and probably most modern xterm and rxvt + # (In screen, only short_tab_title is used) +-# Limited support for Apple Terminal (Terminal can't set window and tab separately) + function title { + setopt localoptions nopromptsubst + +@@ -17,7 +16,7 @@ function title { + : ${2=$1} + + case "$TERM" in +- cygwin|xterm*|putty*|rxvt*|konsole*|ansi|mlterm*|alacritty*|st*|foot*|contour*|wezterm*) ++ cygwin|xterm*|putty*|rxvt*|konsole*|ansi|mlterm*|alacritty*|st*|foot*|contour*|wezterm*|nsterm*) + print -Pn "\e]2;${2:q}\a" # set window name + print -Pn "\e]1;${1:q}\a" # set tab name + ;; +@@ -26,10 +25,12 @@ function title { + print -Pn "\ek${1:q}\e\\" # set screen hardstatus/tmux window name if `allow-rename` is on + ;; + *) +- if [[ "$TERM_PROGRAM" == "iTerm.app" ]]; then ++ case "$TERM_PROGRAM" in ++ "iTerm.app"|"Apple_Terminal") + print -Pn "\e]2;${2:q}\a" # set window name + print -Pn "\e]1;${1:q}\a" # set tab name +- else ++ ;; ++ *) + # Try to use terminfo to set the title if the feature is available + if (( ${+terminfo[fsl]} && ${+terminfo[tsl]} )); then + # Emit the capabilities with echoti so terminfo does its own parameter +@@ -39,7 +40,8 @@ function title { + print -Pn "$1" + echoti fsl + fi +- fi ++ ;; ++ esac + ;; + esac + } diff --git a/tasks/ohmyzsh__ohmyzsh-14172/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14172/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14172/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14172/task.toml b/tasks/ohmyzsh__ohmyzsh-14172/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2470bb4ab02bc735e74bb6b8e1412bceb1661f25 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14172/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14172" +description = "fix(termsupport): improve Apple Terminal support" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "083c339e0622bfc144b66ebf1a2e8dbe7d2ada0d" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14172" +source_access = "auto" +built_at = "2026-11-16T16:09:56.867266+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:364f1ef2ffbc742b002a363aa85426689d108763b8e94e677ae6a9b546fd77ee" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-13T08:41:25Z" +diff_format = "unified" +context_files = [ + "lib/termsupport.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 12 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.002524+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d454cbc252e68947c2ba04ada372685ebad17dfd15ac620cf3d4535e0ca46f8a" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14172/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14172/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14172/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14172/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14172/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d8860d1a5fe0376b1c33101f4034f148e02c4da1 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14172/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** fix(termsupport): improve Apple Terminal support + +## Description + +## Standards checklist: + + + +- [X] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [X] The code follows the code style guide detailed in the wiki. +- [X] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [X] The code is efficient, to the best of my ability, and does not waste computer resources. +- [X] The code is stable and I have tested it myself, to the best of my abilities. +- [x] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- `nsterm` is the "correct" `$TERM` for Apple's Terminal.app, so add it to the list of good terminal emulators. +- Apple's Terminal.app uses the same window/tab title sequences as iTerm.app (status line columns 2 and 1, respectively), so give it the same treatment as iTerm for window title. + +## Other comments: + +This patch was written in 2022, and I rebased it today to submit as PR. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `083c339e0622`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14172/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14172/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..3d8393d3a25436a7a4782aaac579999d7c63d876 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14172/tests/oracle.patch @@ -0,0 +1,46 @@ +diff --git a/lib/termsupport.zsh b/lib/termsupport.zsh +index 6af8fe73..c2623887 100644 +--- a/lib/termsupport.zsh ++++ b/lib/termsupport.zsh +@@ -5,7 +5,6 @@ + # See: http://www.faqs.org/docs/Linux-mini/Xterm-Title.html#ss3.1 + # Fully supports screen, iterm, and probably most modern xterm and rxvt + # (In screen, only short_tab_title is used) +-# Limited support for Apple Terminal (Terminal can't set window and tab separately) + function title { + setopt localoptions nopromptsubst + +@@ -17,7 +16,7 @@ function title { + : ${2=$1} + + case "$TERM" in +- cygwin|xterm*|putty*|rxvt*|konsole*|ansi|mlterm*|alacritty*|st*|foot*|contour*|wezterm*) ++ cygwin|xterm*|putty*|rxvt*|konsole*|ansi|mlterm*|alacritty*|st*|foot*|contour*|wezterm*|nsterm*) + print -Pn "\e]2;${2:q}\a" # set window name + print -Pn "\e]1;${1:q}\a" # set tab name + ;; +@@ -26,10 +25,12 @@ function title { + print -Pn "\ek${1:q}\e\\" # set screen hardstatus/tmux window name if `allow-rename` is on + ;; + *) +- if [[ "$TERM_PROGRAM" == "iTerm.app" ]]; then ++ case "$TERM_PROGRAM" in ++ "iTerm.app"|"Apple_Terminal") + print -Pn "\e]2;${2:q}\a" # set window name + print -Pn "\e]1;${1:q}\a" # set tab name +- else ++ ;; ++ *) + # Try to use terminfo to set the title if the feature is available + if (( ${+terminfo[fsl]} && ${+terminfo[tsl]} )); then + # Emit the capabilities with echoti so terminfo does its own parameter +@@ -39,7 +40,8 @@ function title { + print -Pn "$1" + echoti fsl + fi +- fi ++ ;; ++ esac + ;; + esac + } diff --git a/tasks/ohmyzsh__ohmyzsh-14172/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14172/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b6fde1406eeeb5d5d5093a28e442c8d316c4dca9 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14172/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 083c339e0622bfc144b66ebf1a2e8dbe7d2ada0d > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14172/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14172/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14172/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14173/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14173/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2d2f160ca86e5c7741142ee793ed3fb408634c90 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14173/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 42a4ccb1b14dbeffe81259105a5243b4f4cb618e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 42a4ccb1b14dbeffe81259105a5243b4f4cb618e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 42a4ccb1b14dbeffe81259105a5243b4f4cb618e \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14173/instruction.md b/tasks/ohmyzsh__ohmyzsh-14173/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ccc44e0dd25d85c41f1889305ccda18a1d0671a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14173/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** fix(ruby): preserve special characters in rfind filenames + +## Description + +## Changes + +`rfind needle` fails when a Ruby filename contains spaces, quotes, or a newline: `xargs` splits or reinterprets the filename before passing it to `grep`. + +Use `find -print0` and `xargs -0` to preserve filenames, and update the README's alias row. Add a standalone regression test following the existing plugin test style. + +## Validation + +On macOS with zsh 5.9, `zsh -f plugins/ruby/tests/rfind.test.zsh` passes all six cases. Four fail against the original alias. The CI syntax-check scope and the new test script also pass locally (594 files). `git diff --check` passes. Linux execution is left to CI. + +## Standards checklist + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed the instructions. +- [x] The code follows the existing plugin style. +- [x] The changes are compatible with the project's MIT license. +- [x] AI assistance is disclosed below. +- [x] The code is efficient and does not add dependencies. +- [x] The change has been tested locally. +- [x] No new aliases are introduced. + +## Other comments + +Codex helped find the bug, make the change, and run the tests. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `42a4ccb1b14d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14173/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14173/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d36a14133a4de5a72b694621c681b8fe603397dd --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14173/solution/patch.diff @@ -0,0 +1,64 @@ +diff --git a/plugins/ruby/README.md b/plugins/ruby/README.md +index 59d839c5..d77b8543 100644 +--- a/plugins/ruby/README.md ++++ b/plugins/ruby/README.md +@@ -14,7 +14,7 @@ plugins=(... ruby) + | ------- | -------------------------------------- | ---------------------------------------------------- | + | rb | `ruby` | The Ruby command | + | sgem | `sudo gem` | Run sudo gem on the system ruby, not the active ruby | +-| rfind | `find . -name "*.rb" \| xargs grep -n` | Find ruby file | ++| rfind | `find . -name "*.rb" -print0 \| xargs -0 grep -n` | Find ruby file | + | rrun | `ruby -e` | Execute some code: E.g: `rrun "puts 'Hello world!'"` | + | rserver | `ruby -e httpd . -p 8080` | Start HTTP Webrick serving local directory/files | + | gein | `gem install` | Install a gem into the local repository | +diff --git a/plugins/ruby/ruby.plugin.zsh b/plugins/ruby/ruby.plugin.zsh +index e09b22c7..160852b4 100644 +--- a/plugins/ruby/ruby.plugin.zsh ++++ b/plugins/ruby/ruby.plugin.zsh +@@ -2,7 +2,7 @@ + alias sgem='sudo gem' + + # Find ruby file +-alias rfind='find . -name "*.rb" | xargs grep -n' ++alias rfind='find . -name "*.rb" -print0 | xargs -0 grep -n' + + # Shorthand Ruby + alias rb="ruby" +diff --git a/plugins/ruby/tests/rfind.test.zsh b/plugins/ruby/tests/rfind.test.zsh +new file mode 100644 +index 00000000..6b3d06de +--- /dev/null ++++ b/plugins/ruby/tests/rfind.test.zsh +@@ -0,0 +1,32 @@ ++#!/usr/bin/env zsh ++ ++emulate -LR zsh ++ ++source "${1:-${0:A:h:h}/ruby.plugin.zsh}" ++ ++test_dir=$(mktemp -d) || exit 1 ++trap 'command rm -rf -- "$test_dir"' EXIT ++ ++typeset -i failures=0 tests=0 ++typeset filename output ++ ++for filename in plain.rb 'file with spaces.rb' "single'quote.rb" 'double"quote.rb' $'line\nbreak.rb' 'unicode-ą.rb'; do ++ print -r -- 'needle' >| "$test_dir/$filename" ++ output=$(cd "$test_dir" && rfind needle 2> "$test_dir/stderr") ++ actual_status=$? ++ (( tests++ )) ++ ++ if [[ $actual_status == 0 && $output == '1:needle' && ! -s "$test_dir/stderr" ]]; then ++ print -r -- "PASS: ${(qqq)filename}" ++ else ++ print -u2 -r -- "FAIL: ${(qqq)filename} (status $actual_status)" ++ print -u2 -r -- " stdout: ${(qqq)output}" ++ print -u2 -r -- " stderr: $(<"$test_dir/stderr")" ++ (( failures++ )) ++ fi ++ ++ command rm -- "$test_dir/$filename" ++done ++ ++print -r -- "$tests tests, $failures failures" ++(( failures == 0 )) diff --git a/tasks/ohmyzsh__ohmyzsh-14173/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14173/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14173/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14173/task.toml b/tasks/ohmyzsh__ohmyzsh-14173/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6eedd5e2f5559076affbe19b445ee6c6ab93e5be --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14173/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14173" +description = "fix(ruby): preserve special characters in rfind filenames" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "42a4ccb1b14dbeffe81259105a5243b4f4cb618e" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14173" +source_access = "auto" +built_at = "2026-11-16T16:09:56.884628+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:cbc99788d46ee410aac53f6943350e66b8799dabb37ac0f3aab51b427299250b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-11T22:46:22Z" +diff_format = "unified" +context_files = [ + "plugins/ruby/README.md", + "plugins/ruby/ruby.plugin.zsh", + "plugins/ruby/tests/rfind.test.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 36 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.003059+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d7de01c73d23027acb94bdaa200f519da3f5f6e033582e108635ce56b8dcc4ee" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14173/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14173/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14173/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14173/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14173/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ccc44e0dd25d85c41f1889305ccda18a1d0671a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14173/tests/instruction.md @@ -0,0 +1,35 @@ +# Issue + +**Title:** fix(ruby): preserve special characters in rfind filenames + +## Description + +## Changes + +`rfind needle` fails when a Ruby filename contains spaces, quotes, or a newline: `xargs` splits or reinterprets the filename before passing it to `grep`. + +Use `find -print0` and `xargs -0` to preserve filenames, and update the README's alias row. Add a standalone regression test following the existing plugin test style. + +## Validation + +On macOS with zsh 5.9, `zsh -f plugins/ruby/tests/rfind.test.zsh` passes all six cases. Four fail against the original alias. The CI syntax-check scope and the new test script also pass locally (594 files). `git diff --check` passes. Linux execution is left to CI. + +## Standards checklist + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed the instructions. +- [x] The code follows the existing plugin style. +- [x] The changes are compatible with the project's MIT license. +- [x] AI assistance is disclosed below. +- [x] The code is efficient and does not add dependencies. +- [x] The change has been tested locally. +- [x] No new aliases are introduced. + +## Other comments + +Codex helped find the bug, make the change, and run the tests. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `42a4ccb1b14d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14173/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14173/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d36a14133a4de5a72b694621c681b8fe603397dd --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14173/tests/oracle.patch @@ -0,0 +1,64 @@ +diff --git a/plugins/ruby/README.md b/plugins/ruby/README.md +index 59d839c5..d77b8543 100644 +--- a/plugins/ruby/README.md ++++ b/plugins/ruby/README.md +@@ -14,7 +14,7 @@ plugins=(... ruby) + | ------- | -------------------------------------- | ---------------------------------------------------- | + | rb | `ruby` | The Ruby command | + | sgem | `sudo gem` | Run sudo gem on the system ruby, not the active ruby | +-| rfind | `find . -name "*.rb" \| xargs grep -n` | Find ruby file | ++| rfind | `find . -name "*.rb" -print0 \| xargs -0 grep -n` | Find ruby file | + | rrun | `ruby -e` | Execute some code: E.g: `rrun "puts 'Hello world!'"` | + | rserver | `ruby -e httpd . -p 8080` | Start HTTP Webrick serving local directory/files | + | gein | `gem install` | Install a gem into the local repository | +diff --git a/plugins/ruby/ruby.plugin.zsh b/plugins/ruby/ruby.plugin.zsh +index e09b22c7..160852b4 100644 +--- a/plugins/ruby/ruby.plugin.zsh ++++ b/plugins/ruby/ruby.plugin.zsh +@@ -2,7 +2,7 @@ + alias sgem='sudo gem' + + # Find ruby file +-alias rfind='find . -name "*.rb" | xargs grep -n' ++alias rfind='find . -name "*.rb" -print0 | xargs -0 grep -n' + + # Shorthand Ruby + alias rb="ruby" +diff --git a/plugins/ruby/tests/rfind.test.zsh b/plugins/ruby/tests/rfind.test.zsh +new file mode 100644 +index 00000000..6b3d06de +--- /dev/null ++++ b/plugins/ruby/tests/rfind.test.zsh +@@ -0,0 +1,32 @@ ++#!/usr/bin/env zsh ++ ++emulate -LR zsh ++ ++source "${1:-${0:A:h:h}/ruby.plugin.zsh}" ++ ++test_dir=$(mktemp -d) || exit 1 ++trap 'command rm -rf -- "$test_dir"' EXIT ++ ++typeset -i failures=0 tests=0 ++typeset filename output ++ ++for filename in plain.rb 'file with spaces.rb' "single'quote.rb" 'double"quote.rb' $'line\nbreak.rb' 'unicode-ą.rb'; do ++ print -r -- 'needle' >| "$test_dir/$filename" ++ output=$(cd "$test_dir" && rfind needle 2> "$test_dir/stderr") ++ actual_status=$? ++ (( tests++ )) ++ ++ if [[ $actual_status == 0 && $output == '1:needle' && ! -s "$test_dir/stderr" ]]; then ++ print -r -- "PASS: ${(qqq)filename}" ++ else ++ print -u2 -r -- "FAIL: ${(qqq)filename} (status $actual_status)" ++ print -u2 -r -- " stdout: ${(qqq)output}" ++ print -u2 -r -- " stderr: $(<"$test_dir/stderr")" ++ (( failures++ )) ++ fi ++ ++ command rm -- "$test_dir/$filename" ++done ++ ++print -r -- "$tests tests, $failures failures" ++(( failures == 0 )) diff --git a/tasks/ohmyzsh__ohmyzsh-14173/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14173/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..20632ad7ccb7ec595d82e801c12cae199089c12c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14173/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 42a4ccb1b14dbeffe81259105a5243b4f4cb618e > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14173/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14173/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14173/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14175/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14175/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2d2f160ca86e5c7741142ee793ed3fb408634c90 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14175/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 42a4ccb1b14dbeffe81259105a5243b4f4cb618e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 42a4ccb1b14dbeffe81259105a5243b4f4cb618e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 42a4ccb1b14dbeffe81259105a5243b4f4cb618e \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14175/instruction.md b/tasks/ohmyzsh__ohmyzsh-14175/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..299e9815b5d071baf3e40c2643d84511aeae23c1 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14175/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** chore(zsh-syntax-highlighting): update to version e6683f20 + +## Description + +## Description + +Update for **zsh-syntax-highlighting plugin**: update to version . +Check out the [list of changes](https://github.com/zsh-users/zsh-syntax-highlighting/compare/zsh-users:2fc57d6...zsh-users:e6683f2). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `42a4ccb1b14d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14175/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14175/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f064ee16d0ef3259fdb51afa75e1f083c55d3702 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14175/solution/patch.diff @@ -0,0 +1,33 @@ +diff --git a/.github/dependencies.yml b/.github/dependencies.yml +index 0349c5da..aface23a 100644 +--- a/.github/dependencies.yml ++++ b/.github/dependencies.yml +@@ -75,7 +75,7 @@ dependencies: + plugins/zsh-syntax-highlighting: + repo: zsh-users/zsh-syntax-highlighting + branch: master +- version: 2fc57d63067c18b1100ecdbf684fa5baf49459d1 ++ version: e6683f20e5c38d3e5447f45845d04ddda75d0f23 + precopy: | + set -e + version=$(<.version) +diff --git a/plugins/zsh-syntax-highlighting/highlighters/main/main-highlighter.zsh b/plugins/zsh-syntax-highlighting/highlighters/main/main-highlighter.zsh +index 061e2a48..8531e588 100644 +--- a/plugins/zsh-syntax-highlighting/highlighters/main/main-highlighter.zsh ++++ b/plugins/zsh-syntax-highlighting/highlighters/main/main-highlighter.zsh +@@ -1240,9 +1240,14 @@ _zsh_highlight_main_highlighter_check_path() + fi + tmp_path=$tmp_path:a + ++ local candidate_new_tmp_path + while [[ $tmp_path != / ]]; do + [[ -n ${(M)ZSH_HIGHLIGHT_DIRS_BLACKLIST:#$tmp_path} ]] && return 1 +- tmp_path=$tmp_path:h ++ candidate_new_tmp_path=${tmp_path:h} ++ if [[ $candidate_new_tmp_path == $tmp_path ]]; then ++ break ++ fi ++ tmp_path=${candidate_new_tmp_path} + done + + if (( in_command_position )); then diff --git a/tasks/ohmyzsh__ohmyzsh-14175/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14175/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14175/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14175/task.toml b/tasks/ohmyzsh__ohmyzsh-14175/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d62ba7247ab5a42e0f0f101801690699203e81a5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14175/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14175" +description = "chore(zsh-syntax-highlighting): update to version e6683f20" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "42a4ccb1b14dbeffe81259105a5243b4f4cb618e" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14175" +source_access = "auto" +built_at = "2026-11-16T16:09:56.885968+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5617a40ba31894d58bc76e601c29b24293e376e695bdd3e893d7f6e937a637aa" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-11T08:27:56Z" +diff_format = "unified" +context_files = [ + ".github/dependencies.yml", + "plugins/zsh-syntax-highlighting/highlighters/main/main-highlighter.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 9 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.003562+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:d7de01c73d23027acb94bdaa200f519da3f5f6e033582e108635ce56b8dcc4ee" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14175/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14175/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14175/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14175/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14175/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..299e9815b5d071baf3e40c2643d84511aeae23c1 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14175/tests/instruction.md @@ -0,0 +1,14 @@ +# Issue + +**Title:** chore(zsh-syntax-highlighting): update to version e6683f20 + +## Description + +## Description + +Update for **zsh-syntax-highlighting plugin**: update to version . +Check out the [list of changes](https://github.com/zsh-users/zsh-syntax-highlighting/compare/zsh-users:2fc57d6...zsh-users:e6683f2). + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `42a4ccb1b14d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14175/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14175/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f064ee16d0ef3259fdb51afa75e1f083c55d3702 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14175/tests/oracle.patch @@ -0,0 +1,33 @@ +diff --git a/.github/dependencies.yml b/.github/dependencies.yml +index 0349c5da..aface23a 100644 +--- a/.github/dependencies.yml ++++ b/.github/dependencies.yml +@@ -75,7 +75,7 @@ dependencies: + plugins/zsh-syntax-highlighting: + repo: zsh-users/zsh-syntax-highlighting + branch: master +- version: 2fc57d63067c18b1100ecdbf684fa5baf49459d1 ++ version: e6683f20e5c38d3e5447f45845d04ddda75d0f23 + precopy: | + set -e + version=$(<.version) +diff --git a/plugins/zsh-syntax-highlighting/highlighters/main/main-highlighter.zsh b/plugins/zsh-syntax-highlighting/highlighters/main/main-highlighter.zsh +index 061e2a48..8531e588 100644 +--- a/plugins/zsh-syntax-highlighting/highlighters/main/main-highlighter.zsh ++++ b/plugins/zsh-syntax-highlighting/highlighters/main/main-highlighter.zsh +@@ -1240,9 +1240,14 @@ _zsh_highlight_main_highlighter_check_path() + fi + tmp_path=$tmp_path:a + ++ local candidate_new_tmp_path + while [[ $tmp_path != / ]]; do + [[ -n ${(M)ZSH_HIGHLIGHT_DIRS_BLACKLIST:#$tmp_path} ]] && return 1 +- tmp_path=$tmp_path:h ++ candidate_new_tmp_path=${tmp_path:h} ++ if [[ $candidate_new_tmp_path == $tmp_path ]]; then ++ break ++ fi ++ tmp_path=${candidate_new_tmp_path} + done + + if (( in_command_position )); then diff --git a/tasks/ohmyzsh__ohmyzsh-14175/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14175/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..20632ad7ccb7ec595d82e801c12cae199089c12c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14175/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 42a4ccb1b14dbeffe81259105a5243b4f4cb618e > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14175/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14175/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14175/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14176/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14176/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5ae6cc16559ba3a96f778c2ce076be81f00edc09 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14176/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 48feb570f7b7d80cc7554629ba428c520ea8a3d5 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 48feb570f7b7d80cc7554629ba428c520ea8a3d5 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 48feb570f7b7d80cc7554629ba428c520ea8a3d5 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14176/instruction.md b/tasks/ohmyzsh__ohmyzsh-14176/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..19ec6b47de7b0dd266898c8a2707cc651f84cd25 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14176/instruction.md @@ -0,0 +1,150 @@ +# Issue + +**Title:** chore(deps): bump the gha-minor group with 3 updates + +## Description + +Bumps the gha-minor group with 3 updates: [step-security/harden-runner](https://github.com/step-security/harden-runner), [actions/upload-artifact](https://github.com/actions/upload-artifact) and [github/codeql-action/upload-sarif](https://github.com/github/codeql-action). + +Updates `step-security/harden-runner` from 2.21.1 to 2.22.1 +
      +Release notes +

      Sourced from step-security/harden-runner's releases.

      +
      +

      v2.22.1

      +

      What's Changed

      +
        +
      • Fixed security rules not initializing on GHES self-hosted runners
      • +
      • Fixed GHES connectivity in block mode by implicitly allowing the GHES hostname
      • +
      +

      Full Changelog: https://github.com/step-security/harden-runner/compare/v2.22.0...v2.22.1

      +

      v2.22.0

      +

      What's Changed

      +
        +
      • Linux ARM64 support for community tier
      • +
      • GHES support for self-hosted VMs (enterprise tier)
      • +
      • MacOS and Windows runner deny list support for block policy (enterprise tier).
      • +
      +

      Full Changelog: https://github.com/step-security/harden-runner/compare/v2.21.1...v2.22.0

      +
      +
      +
      +Commits +
        +
      • ccd8616 Merge pull request #704 from h0x0er/jatin/ghes-endp
      • +
      • 037ccfd implicitly add ghes endpoint in allowList
      • +
      • e7438c7 Merge pull request #703 from h0x0er/jatin/ghes-codebuild-fixes
      • +
      • afb0b33 fixes for armour rules not getting initialised
      • +
      • 351661c Merge pull request #701 from step-security/rc-44
      • +
      • 1dc7f2e Merge pull request #702 from h0x0er/jatin/ghes-changes-up
      • +
      • af5ca38 simplified ghes config creation
      • +
      • 9a6d710 fix2
      • +
      • 74c65ea fix
      • +
      • ceac816 resovled comments
      • +
      • Additional commits viewable in compare view
      • +
      +
      +
      + +Updates `actions/upload-artifact` from 7.0.1 to 7.0.2 +
      +Release notes +

      Sourced from actions/upload-artifact's releases.

      +
      +

      v7.0.2

      +

      What's Changed

      +
        +
      • Improves artifact download retries when the service returns HTTP 429 (rate limiting), including honoring valid Retry-After headers.
      • +
      • Updates @​actions/artifact to v6.3.1.
      • +
      +

      New Contributors

      + +

      Full Changelog: https://github.com/actions/upload-artifact/compare/v7.0.1...v7.0.2

      +
      +
      +
      +Commits +
        +
      • cf430e0 Merge pull request #822 from actions/tunc-d-prepare-upload-v7-0-2
      • +
      • c2acded chore: prepare v7.0.2 release
      • +
      • 4687c1b Merge pull request #821 from actions/tunc-d-upload-artifact-package-bump
      • +
      • 8cbe1be Bump @​actions/artifact to 6.3.1
      • +
      • See full diff in compare view
      • +
      +
      +
      + +Updates `github/codeql-action/upload-sarif` from 4.38.2 to 4.38.3 +
      +Release notes +

      Sourced from github/codeql-action/upload-sarif's releases.

      +
      +

      v4.38.3

      +
        +
      • Upcoming breaking change: CodeQL version 2.21.2 and earlier were discontinued on 24 September 2026 alongside GitHub Enterprise Server 3.17, and will be unsupported by the next minor release of the CodeQL Action. Added a deprecation warning for customers using these versions of CodeQL. #4188
      • +
      • Update default CodeQL bundle version to 2.27.2. #4203
      • +
      • Fixed a bug where the decision of whether to use a per-language bundle did not account for custom configurations that reference queries outside of compiled CodeQL packs. This issue was caught during internal testing and did not affect any customer repositories. We will resume the roll out of per-language bundles in the coming weeks. #4184
      • +
      +
      +
      +
      +Changelog +

      Sourced from github/codeql-action/upload-sarif's changelog.

      +
      +

      CodeQL Action Changelog

      +

      See the releases page for the relevant changes to the CodeQL CLI and language packs.

      +

      [UNRELEASED]

      +

      No user facing changes.

      +

      4.38.3 - 08 Oct 2026

      +
        +
      • Upcoming breaking change: CodeQL version 2.21.2 and earlier were discontinued on 24 September 2026 alongside GitHub Enterprise Server 3.17, and will be unsupported by the next minor release of the CodeQL Action. Added a deprecation warning for customers using these versions of CodeQL. #4188
      • +
      • Update default CodeQL bundle version to 2.27.2. #4203
      • +
      • Fixed a bug where the decision of whether to use a per-language bundle did not account for custom configurations that reference queries outside of compiled CodeQL packs. This issue was caught during internal testing and did not affect any customer repositories. We will resume the roll out of per-language bundles in the coming weeks. #4184
      • +
      +

      4.38.2 - 24 Sept 2026

      +
        +
      • Update default CodeQL bundle version to 2.27.1. #4160
      • +
      +

      4.38.1 - 18 Sept 2026

      +
        +
      • The CodeQL Action now has experimental support for CodeQL releases for which per-language bundles are available. Per-language bundles support analysis for a single language and are therefore smaller than the combined bundles that allow analysis for all supported languages. As a result, per-language bundles take up less space on disk and are faster to download. We expect to roll this change out to everyone in the coming weeks. #4146
      • +
      +

      4.38.0 - 09 Sept 2026

      +
        +
      • On GitHub-hosted runners, the CodeQL Action now deletes unused CodeQL bundles from the toolcache before downloading a different bundle, which frees up disk space for the analysis. We expect to roll this change out to everyone in September. #4124
      • +
      • The CodeQL Action now supports CodeQL releases that are compatible with Linux Arm64 and downloads the native linux-arm64 CodeQL bundle when available. #4072
      • +
      • Update default CodeQL bundle version to 2.27.0. #4129
      • +
      +

      4.37.9 - 26 Aug 2026

      +
        +
      • Update default CodeQL bundle version to 2.26.4. #4106
      • +
      +

      4.37.8 - 21 Aug 2026

      +

      No user facing changes.

      +

      4.37.7 - 13 Aug 2026

      +
        +
      • Update default CodeQL bundle version to 2.26.3. #4085
      • +
      +

      4.37.6 - 04 Aug 2026

      +
        +
      • Changed the default filepath for the new remote file address format that was introduced in CodeQL Action 4.37.0 / 3.37.0 to .github/codeql-config.yml to align it with the suggested path that is used elsewhere. #4070
      • +
      +

      4.37.5 - 03 Aug 2026

      +
        +
      • Fixed a bug where a network error while streaming the download of the CodeQL bundle could terminate the init Action instead of falling back to downloading the bundle before extracting it. #4061
      • +
      +

      4.37.4 - 29 Jul 2026

      + +
      +

      ... (truncated)

      +
      +
      +Commits +
        +
      • 24c5418 Merge pull request bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14176/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14176/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..19ec6b47de7b0dd266898c8a2707cc651f84cd25 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14176/tests/instruction.md @@ -0,0 +1,150 @@ +# Issue + +**Title:** chore(deps): bump the gha-minor group with 3 updates + +## Description + +Bumps the gha-minor group with 3 updates: [step-security/harden-runner](https://github.com/step-security/harden-runner), [actions/upload-artifact](https://github.com/actions/upload-artifact) and [github/codeql-action/upload-sarif](https://github.com/github/codeql-action). + +Updates `step-security/harden-runner` from 2.21.1 to 2.22.1 +
        +Release notes +

        Sourced from step-security/harden-runner's releases.

        +
        +

        v2.22.1

        +

        What's Changed

        +
          +
        • Fixed security rules not initializing on GHES self-hosted runners
        • +
        • Fixed GHES connectivity in block mode by implicitly allowing the GHES hostname
        • +
        +

        Full Changelog: https://github.com/step-security/harden-runner/compare/v2.22.0...v2.22.1

        +

        v2.22.0

        +

        What's Changed

        +
          +
        • Linux ARM64 support for community tier
        • +
        • GHES support for self-hosted VMs (enterprise tier)
        • +
        • MacOS and Windows runner deny list support for block policy (enterprise tier).
        • +
        +

        Full Changelog: https://github.com/step-security/harden-runner/compare/v2.21.1...v2.22.0

        +
        +
        +
        +Commits +
          +
        • ccd8616 Merge pull request #704 from h0x0er/jatin/ghes-endp
        • +
        • 037ccfd implicitly add ghes endpoint in allowList
        • +
        • e7438c7 Merge pull request #703 from h0x0er/jatin/ghes-codebuild-fixes
        • +
        • afb0b33 fixes for armour rules not getting initialised
        • +
        • 351661c Merge pull request #701 from step-security/rc-44
        • +
        • 1dc7f2e Merge pull request #702 from h0x0er/jatin/ghes-changes-up
        • +
        • af5ca38 simplified ghes config creation
        • +
        • 9a6d710 fix2
        • +
        • 74c65ea fix
        • +
        • ceac816 resovled comments
        • +
        • Additional commits viewable in compare view
        • +
        +
        +
        + +Updates `actions/upload-artifact` from 7.0.1 to 7.0.2 +
        +Release notes +

        Sourced from actions/upload-artifact's releases.

        +
        +

        v7.0.2

        +

        What's Changed

        +
          +
        • Improves artifact download retries when the service returns HTTP 429 (rate limiting), including honoring valid Retry-After headers.
        • +
        • Updates @​actions/artifact to v6.3.1.
        • +
        +

        New Contributors

        + +

        Full Changelog: https://github.com/actions/upload-artifact/compare/v7.0.1...v7.0.2

        +
        +
        +
        +Commits +
          +
        • cf430e0 Merge pull request #822 from actions/tunc-d-prepare-upload-v7-0-2
        • +
        • c2acded chore: prepare v7.0.2 release
        • +
        • 4687c1b Merge pull request #821 from actions/tunc-d-upload-artifact-package-bump
        • +
        • 8cbe1be Bump @​actions/artifact to 6.3.1
        • +
        • See full diff in compare view
        • +
        +
        +
        + +Updates `github/codeql-action/upload-sarif` from 4.38.2 to 4.38.3 +
        +Release notes +

        Sourced from github/codeql-action/upload-sarif's releases.

        +
        +

        v4.38.3

        +
          +
        • Upcoming breaking change: CodeQL version 2.21.2 and earlier were discontinued on 24 September 2026 alongside GitHub Enterprise Server 3.17, and will be unsupported by the next minor release of the CodeQL Action. Added a deprecation warning for customers using these versions of CodeQL. #4188
        • +
        • Update default CodeQL bundle version to 2.27.2. #4203
        • +
        • Fixed a bug where the decision of whether to use a per-language bundle did not account for custom configurations that reference queries outside of compiled CodeQL packs. This issue was caught during internal testing and did not affect any customer repositories. We will resume the roll out of per-language bundles in the coming weeks. #4184
        • +
        +
        +
        +
        +Changelog +

        Sourced from github/codeql-action/upload-sarif's changelog.

        +
        +

        CodeQL Action Changelog

        +

        See the releases page for the relevant changes to the CodeQL CLI and language packs.

        +

        [UNRELEASED]

        +

        No user facing changes.

        +

        4.38.3 - 08 Oct 2026

        +
          +
        • Upcoming breaking change: CodeQL version 2.21.2 and earlier were discontinued on 24 September 2026 alongside GitHub Enterprise Server 3.17, and will be unsupported by the next minor release of the CodeQL Action. Added a deprecation warning for customers using these versions of CodeQL. #4188
        • +
        • Update default CodeQL bundle version to 2.27.2. #4203
        • +
        • Fixed a bug where the decision of whether to use a per-language bundle did not account for custom configurations that reference queries outside of compiled CodeQL packs. This issue was caught during internal testing and did not affect any customer repositories. We will resume the roll out of per-language bundles in the coming weeks. #4184
        • +
        +

        4.38.2 - 24 Sept 2026

        +
          +
        • Update default CodeQL bundle version to 2.27.1. #4160
        • +
        +

        4.38.1 - 18 Sept 2026

        +
          +
        • The CodeQL Action now has experimental support for CodeQL releases for which per-language bundles are available. Per-language bundles support analysis for a single language and are therefore smaller than the combined bundles that allow analysis for all supported languages. As a result, per-language bundles take up less space on disk and are faster to download. We expect to roll this change out to everyone in the coming weeks. #4146
        • +
        +

        4.38.0 - 09 Sept 2026

        +
          +
        • On GitHub-hosted runners, the CodeQL Action now deletes unused CodeQL bundles from the toolcache before downloading a different bundle, which frees up disk space for the analysis. We expect to roll this change out to everyone in September. #4124
        • +
        • The CodeQL Action now supports CodeQL releases that are compatible with Linux Arm64 and downloads the native linux-arm64 CodeQL bundle when available. #4072
        • +
        • Update default CodeQL bundle version to 2.27.0. #4129
        • +
        +

        4.37.9 - 26 Aug 2026

        +
          +
        • Update default CodeQL bundle version to 2.26.4. #4106
        • +
        +

        4.37.8 - 21 Aug 2026

        +

        No user facing changes.

        +

        4.37.7 - 13 Aug 2026

        +
          +
        • Update default CodeQL bundle version to 2.26.3. #4085
        • +
        +

        4.37.6 - 04 Aug 2026

        +
          +
        • Changed the default filepath for the new remote file address format that was introduced in CodeQL Action 4.37.0 / 3.37.0 to .github/codeql-config.yml to align it with the suggested path that is used elsewhere. #4070
        • +
        +

        4.37.5 - 03 Aug 2026

        +
          +
        • Fixed a bug where a network error while streaming the download of the CodeQL bundle could terminate the init Action instead of falling back to downloading the bundle before extracting it. #4061
        • +
        +

        4.37.4 - 29 Jul 2026

        + +
        +

        ... (truncated)

        +
        +
        +Commits +
          +
        • 24c5418 Merge pull request "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14176/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14176/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14176/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14188/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14188/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ff0cb3812d01fadaeedcc25c22ddcc34bcd58cd5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14188/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 964ddf789b022b6958b27d02d7fa54f552de21e9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 964ddf789b022b6958b27d02d7fa54f552de21e9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 964ddf789b022b6958b27d02d7fa54f552de21e9 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14188/instruction.md b/tasks/ohmyzsh__ohmyzsh-14188/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..74d399e3369450c4dd5f34b5565b103a3591620b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14188/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** fix(docker): create completions cache dir if missing + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. (No new aliases.) + +## Changes: + +- . When the docker plugin is loaded by a standalone plugin manager (e.g. antigen), the Oh My Zsh core is not sourced, so `$ZSH_CACHE_DIR/completions` is never created. The subsequent `zf_mv`/`cp` of the completion file then fails with `tee: .../cache//completions/_docker: No such file or directory`. +- Ensure the directory exists before writing into it, mirroring what the core already does in `oh-my-zsh.sh`. + +## Other comments: + +- AI-assisted contribution: yes, with manual verification. +- The one-line guard `[[ -d "$ZSH_CACHE_DIR/completions" ]] || mkdir -p "$ZSH_CACHE_DIR/completions"` is idempotent and a no-op when the core has already created the directory. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `964ddf789b02`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14188/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14188/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6e951e9e431368aec197407d562bedbf28eeb64e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14188/solution/patch.diff @@ -0,0 +1,16 @@ +diff --git a/plugins/docker/docker.plugin.zsh b/plugins/docker/docker.plugin.zsh +index c738f315..88687438 100644 +--- a/plugins/docker/docker.plugin.zsh ++++ b/plugins/docker/docker.plugin.zsh +@@ -48,6 +48,11 @@ fi + 0="${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}" + 0="${${(M)0:#/*}:-$PWD/$0}" + ++# Make sure the cache directory exists; when the plugin is loaded by a ++# standalone plugin manager (e.g. antigen) the core is not sourced, so ++# $ZSH_CACHE_DIR/completions may not have been created yet (#13679). ++[[ -d "$ZSH_CACHE_DIR/completions" ]] || mkdir -p "$ZSH_CACHE_DIR/completions" ++ + # If the completion file doesn't exist yet, we need to autoload it and + # bind it to `docker`. Otherwise, compinit will have already done that. + if [[ ! -f "$ZSH_CACHE_DIR/completions/_docker" ]]; then diff --git a/tasks/ohmyzsh__ohmyzsh-14188/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14188/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14188/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14188/task.toml b/tasks/ohmyzsh__ohmyzsh-14188/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f171e3d91705feec9c796f7ffac3982adacf3977 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14188/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14188" +description = "fix(docker): create completions cache dir if missing (closes #13679)" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "964ddf789b022b6958b27d02d7fa54f552de21e9" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14188" +source_access = "auto" +built_at = "2026-11-16T16:09:56.861847+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:64d2ad8a47d9d543c521f50372b3bb72fd1752d6dbb9fb3c6302a91f680f527f" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-20T00:17:07Z" +diff_format = "unified" +context_files = [ + "plugins/docker/docker.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.004651+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1d7ecedb3ea5d441072e90d5fb5399a881952ea02abdcb33f024e9913a424a8d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14188/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14188/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14188/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14188/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14188/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..74d399e3369450c4dd5f34b5565b103a3591620b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14188/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** fix(docker): create completions cache dir if missing + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. (No new aliases.) + +## Changes: + +- . When the docker plugin is loaded by a standalone plugin manager (e.g. antigen), the Oh My Zsh core is not sourced, so `$ZSH_CACHE_DIR/completions` is never created. The subsequent `zf_mv`/`cp` of the completion file then fails with `tee: .../cache//completions/_docker: No such file or directory`. +- Ensure the directory exists before writing into it, mirroring what the core already does in `oh-my-zsh.sh`. + +## Other comments: + +- AI-assisted contribution: yes, with manual verification. +- The one-line guard `[[ -d "$ZSH_CACHE_DIR/completions" ]] || mkdir -p "$ZSH_CACHE_DIR/completions"` is idempotent and a no-op when the core has already created the directory. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `964ddf789b02`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14188/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14188/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6e951e9e431368aec197407d562bedbf28eeb64e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14188/tests/oracle.patch @@ -0,0 +1,16 @@ +diff --git a/plugins/docker/docker.plugin.zsh b/plugins/docker/docker.plugin.zsh +index c738f315..88687438 100644 +--- a/plugins/docker/docker.plugin.zsh ++++ b/plugins/docker/docker.plugin.zsh +@@ -48,6 +48,11 @@ fi + 0="${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}" + 0="${${(M)0:#/*}:-$PWD/$0}" + ++# Make sure the cache directory exists; when the plugin is loaded by a ++# standalone plugin manager (e.g. antigen) the core is not sourced, so ++# $ZSH_CACHE_DIR/completions may not have been created yet (#13679). ++[[ -d "$ZSH_CACHE_DIR/completions" ]] || mkdir -p "$ZSH_CACHE_DIR/completions" ++ + # If the completion file doesn't exist yet, we need to autoload it and + # bind it to `docker`. Otherwise, compinit will have already done that. + if [[ ! -f "$ZSH_CACHE_DIR/completions/_docker" ]]; then diff --git a/tasks/ohmyzsh__ohmyzsh-14188/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14188/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7ca4718f25d4b42fa6fd34fe9a8595095325ab5d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14188/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 964ddf789b022b6958b27d02d7fa54f552de21e9 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14188/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14188/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14188/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14190/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14190/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ff0cb3812d01fadaeedcc25c22ddcc34bcd58cd5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14190/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 964ddf789b022b6958b27d02d7fa54f552de21e9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 964ddf789b022b6958b27d02d7fa54f552de21e9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 964ddf789b022b6958b27d02d7fa54f552de21e9 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14190/instruction.md b/tasks/ohmyzsh__ohmyzsh-14190/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3a1109e420415598636e937c33ce372ab6cc4c36 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14190/instruction.md @@ -0,0 +1,41 @@ +# Issue + +**Title:** fix(jsontools): read Node.js input from stdin + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- With `JSONTOOLS_METHOD=node`, `pp_json`, `is_json`, `urlencode_json` and `urldecode_json` now read their input from stdin (`fs.readFileSync(0, "utf8")`) instead of receiving it as a command-line argument through `xargs -0`. + - Passing the whole document as one argument hits the kernel's per-argument limit (128 KiB on Linux), so larger JSON failed with `Argument list too long`. + - Input starting with `--` was parsed by node as one of its own options (e.g. `--version` failed with `bad option`, `--inspect` started the debugger). + - `xargs -0` also split the input on NUL bytes, so only the first chunk was checked (e.g. `printf '1\0002' | is_json` printed `true`). +- Add `plugins/jsontools/tests/jsontools.test.zsh`, covering a 256 KiB document with all four functions, input starting with `--`, invalid JSON and NUL bytes. + +## Other comments: + +Only the `node` method changes; the `python3`, `python` and `ruby` methods already read from stdin. + +Tested with: + +```sh +zsh -df plugins/jsontools/tests/jsontools.test.zsh +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `964ddf789b02`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14190/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14190/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d5dac592d01faa81b007375aca7250bc906b6129 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14190/solution/patch.diff @@ -0,0 +1,113 @@ +diff --git a/plugins/jsontools/jsontools.plugin.zsh b/plugins/jsontools/jsontools.plugin.zsh +index 49828d32..993138d2 100644 +--- a/plugins/jsontools/jsontools.plugin.zsh ++++ b/plugins/jsontools/jsontools.plugin.zsh +@@ -22,14 +22,17 @@ fi + # Define json tools for each method + case "$JSONTOOLS_METHOD" in + node) +- # node doesn't make it easy to deal with stdin, so we pass it as an argument with xargs -0 ++ # Read stdin directly so input is not limited by command-line argument size. + function pp_json() { +- xargs -0 node -e 'console.log(JSON.stringify(JSON.parse(process.argv[1]), null, 4));' ++ node -e ' ++ const input = require("fs").readFileSync(0, "utf8"); ++ console.log(JSON.stringify(JSON.parse(input), null, 4)); ++ ' + } + function is_json() { +- xargs -0 node -e ' ++ node -e ' + try { +- json = JSON.parse(process.argv[1]); ++ JSON.parse(require("fs").readFileSync(0, "utf8")); + console.log("true"); + process.exit(0); + } catch (e) { +@@ -39,10 +42,14 @@ case "$JSONTOOLS_METHOD" in + ' + } + function urlencode_json() { +- xargs -0 node -e "console.log(encodeURIComponent(process.argv[1]))" ++ node -e ' ++ console.log(encodeURIComponent(require("fs").readFileSync(0, "utf8"))); ++ ' + } + function urldecode_json() { +- xargs -0 node -e "console.log(decodeURIComponent(process.argv[1]))" ++ node -e ' ++ console.log(decodeURIComponent(require("fs").readFileSync(0, "utf8"))); ++ ' + } + ;; + python3) +diff --git a/plugins/jsontools/tests/jsontools.test.zsh b/plugins/jsontools/tests/jsontools.test.zsh +new file mode 100644 +index 00000000..3b594c16 +--- /dev/null ++++ b/plugins/jsontools/tests/jsontools.test.zsh +@@ -0,0 +1,64 @@ ++#!/usr/bin/env zsh ++ ++# Run with: zsh -df plugins/jsontools/tests/jsontools.test.zsh ++emulate -L zsh ++setopt err_return ++ ++(( $+commands[node] )) || { ++ print -u2 'These tests require Node.js.' ++ exit 1 ++} ++ ++JSONTOOLS_METHOD=node ++source "${0:A:h:h}/jsontools.plugin.zsh" ++local test_dir=$(mktemp -d) ++ ++check_output() { ++ local tool=$1 description=$2 expected_status=${3:-0} ++ local -i result=0 ++ $tool < "$test_dir/input" > "$test_dir/actual" || result=$? ++ if (( result != expected_status )) \ ++ || ! cmp -s "$test_dir/expected" "$test_dir/actual"; then ++ print -u2 -r -- "FAIL: $description ($tool exited $result)" ++ return 1 ++ fi ++ print -r -- "PASS: $description" ++} ++ ++{ ++ print -rn -- '{"value":42}' > "$test_dir/input" ++ printf '{\n "value": 42\n}\n' > "$test_dir/expected" ++ check_output pp_json 'pretty-print a small document' ++ ++ # Larger than the 128 KiB limit for a single command-line argument. ++ local large_value=${(l:262144::x:):-} ++ print -rn -- '{"value":"'"$large_value"'"}' > "$test_dir/input" ++ printf '{\n "value": "%s"\n}\n' "$large_value" > "$test_dir/expected" ++ check_output pp_json 'pretty-print a large document' ++ print -r -- true > "$test_dir/expected" ++ check_output is_json 'validate a large document' ++ ++ print -r -- '%7B%22value%22%3A%22'"$large_value"'%22%7D' \ ++ > "$test_dir/expected" ++ check_output urlencode_json 'encode a large document' ++ local encoded=$(< "$test_dir/expected") ++ print -rn -- "$encoded" > "$test_dir/input" ++ print -r -- '{"value":"'"$large_value"'"}' > "$test_dir/expected" ++ check_output urldecode_json 'decode a large document' ++ ++ # Passed as an argument, node used to parse this as its own option. ++ print -rn -- '--version' > "$test_dir/input" ++ print -r -- '--version' > "$test_dir/expected" ++ check_output urlencode_json 'encode input that starts with --' ++ ++ print -rn -- '{invalid}' > "$test_dir/input" ++ print -r -- false > "$test_dir/expected" ++ check_output is_json 'reject invalid JSON' 1 ++ ++ printf '1\0002' > "$test_dir/input" ++ check_output is_json 'reject input with NUL bytes' 1 ++ ++ print 'All jsontools Node.js tests passed.' ++} always { ++ rm -rf -- "$test_dir" ++} diff --git a/tasks/ohmyzsh__ohmyzsh-14190/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14190/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14190/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14190/task.toml b/tasks/ohmyzsh__ohmyzsh-14190/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e007cbc9a86e8d3bf807fc21bde7119994be9e39 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14190/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14190" +description = "fix(jsontools): read Node.js input from stdin" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "964ddf789b022b6958b27d02d7fa54f552de21e9" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14190" +source_access = "auto" +built_at = "2026-11-16T16:09:56.858825+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:34997c1a5f6a5a7278eba4ab44db17814066c5518b64804fcc0f15545f70d7e8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-20T00:21:45Z" +diff_format = "unified" +context_files = [ + "plugins/jsontools/jsontools.plugin.zsh", + "plugins/jsontools/tests/jsontools.test.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 83 +difficulty = "large" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.005124+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1d7ecedb3ea5d441072e90d5fb5399a881952ea02abdcb33f024e9913a424a8d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14190/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14190/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14190/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14190/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14190/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3a1109e420415598636e937c33ce372ab6cc4c36 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14190/tests/instruction.md @@ -0,0 +1,41 @@ +# Issue + +**Title:** fix(jsontools): read Node.js input from stdin + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- With `JSONTOOLS_METHOD=node`, `pp_json`, `is_json`, `urlencode_json` and `urldecode_json` now read their input from stdin (`fs.readFileSync(0, "utf8")`) instead of receiving it as a command-line argument through `xargs -0`. + - Passing the whole document as one argument hits the kernel's per-argument limit (128 KiB on Linux), so larger JSON failed with `Argument list too long`. + - Input starting with `--` was parsed by node as one of its own options (e.g. `--version` failed with `bad option`, `--inspect` started the debugger). + - `xargs -0` also split the input on NUL bytes, so only the first chunk was checked (e.g. `printf '1\0002' | is_json` printed `true`). +- Add `plugins/jsontools/tests/jsontools.test.zsh`, covering a 256 KiB document with all four functions, input starting with `--`, invalid JSON and NUL bytes. + +## Other comments: + +Only the `node` method changes; the `python3`, `python` and `ruby` methods already read from stdin. + +Tested with: + +```sh +zsh -df plugins/jsontools/tests/jsontools.test.zsh +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `964ddf789b02`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14190/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14190/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d5dac592d01faa81b007375aca7250bc906b6129 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14190/tests/oracle.patch @@ -0,0 +1,113 @@ +diff --git a/plugins/jsontools/jsontools.plugin.zsh b/plugins/jsontools/jsontools.plugin.zsh +index 49828d32..993138d2 100644 +--- a/plugins/jsontools/jsontools.plugin.zsh ++++ b/plugins/jsontools/jsontools.plugin.zsh +@@ -22,14 +22,17 @@ fi + # Define json tools for each method + case "$JSONTOOLS_METHOD" in + node) +- # node doesn't make it easy to deal with stdin, so we pass it as an argument with xargs -0 ++ # Read stdin directly so input is not limited by command-line argument size. + function pp_json() { +- xargs -0 node -e 'console.log(JSON.stringify(JSON.parse(process.argv[1]), null, 4));' ++ node -e ' ++ const input = require("fs").readFileSync(0, "utf8"); ++ console.log(JSON.stringify(JSON.parse(input), null, 4)); ++ ' + } + function is_json() { +- xargs -0 node -e ' ++ node -e ' + try { +- json = JSON.parse(process.argv[1]); ++ JSON.parse(require("fs").readFileSync(0, "utf8")); + console.log("true"); + process.exit(0); + } catch (e) { +@@ -39,10 +42,14 @@ case "$JSONTOOLS_METHOD" in + ' + } + function urlencode_json() { +- xargs -0 node -e "console.log(encodeURIComponent(process.argv[1]))" ++ node -e ' ++ console.log(encodeURIComponent(require("fs").readFileSync(0, "utf8"))); ++ ' + } + function urldecode_json() { +- xargs -0 node -e "console.log(decodeURIComponent(process.argv[1]))" ++ node -e ' ++ console.log(decodeURIComponent(require("fs").readFileSync(0, "utf8"))); ++ ' + } + ;; + python3) +diff --git a/plugins/jsontools/tests/jsontools.test.zsh b/plugins/jsontools/tests/jsontools.test.zsh +new file mode 100644 +index 00000000..3b594c16 +--- /dev/null ++++ b/plugins/jsontools/tests/jsontools.test.zsh +@@ -0,0 +1,64 @@ ++#!/usr/bin/env zsh ++ ++# Run with: zsh -df plugins/jsontools/tests/jsontools.test.zsh ++emulate -L zsh ++setopt err_return ++ ++(( $+commands[node] )) || { ++ print -u2 'These tests require Node.js.' ++ exit 1 ++} ++ ++JSONTOOLS_METHOD=node ++source "${0:A:h:h}/jsontools.plugin.zsh" ++local test_dir=$(mktemp -d) ++ ++check_output() { ++ local tool=$1 description=$2 expected_status=${3:-0} ++ local -i result=0 ++ $tool < "$test_dir/input" > "$test_dir/actual" || result=$? ++ if (( result != expected_status )) \ ++ || ! cmp -s "$test_dir/expected" "$test_dir/actual"; then ++ print -u2 -r -- "FAIL: $description ($tool exited $result)" ++ return 1 ++ fi ++ print -r -- "PASS: $description" ++} ++ ++{ ++ print -rn -- '{"value":42}' > "$test_dir/input" ++ printf '{\n "value": 42\n}\n' > "$test_dir/expected" ++ check_output pp_json 'pretty-print a small document' ++ ++ # Larger than the 128 KiB limit for a single command-line argument. ++ local large_value=${(l:262144::x:):-} ++ print -rn -- '{"value":"'"$large_value"'"}' > "$test_dir/input" ++ printf '{\n "value": "%s"\n}\n' "$large_value" > "$test_dir/expected" ++ check_output pp_json 'pretty-print a large document' ++ print -r -- true > "$test_dir/expected" ++ check_output is_json 'validate a large document' ++ ++ print -r -- '%7B%22value%22%3A%22'"$large_value"'%22%7D' \ ++ > "$test_dir/expected" ++ check_output urlencode_json 'encode a large document' ++ local encoded=$(< "$test_dir/expected") ++ print -rn -- "$encoded" > "$test_dir/input" ++ print -r -- '{"value":"'"$large_value"'"}' > "$test_dir/expected" ++ check_output urldecode_json 'decode a large document' ++ ++ # Passed as an argument, node used to parse this as its own option. ++ print -rn -- '--version' > "$test_dir/input" ++ print -r -- '--version' > "$test_dir/expected" ++ check_output urlencode_json 'encode input that starts with --' ++ ++ print -rn -- '{invalid}' > "$test_dir/input" ++ print -r -- false > "$test_dir/expected" ++ check_output is_json 'reject invalid JSON' 1 ++ ++ printf '1\0002' > "$test_dir/input" ++ check_output is_json 'reject input with NUL bytes' 1 ++ ++ print 'All jsontools Node.js tests passed.' ++} always { ++ rm -rf -- "$test_dir" ++} diff --git a/tasks/ohmyzsh__ohmyzsh-14190/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14190/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7ca4718f25d4b42fa6fd34fe9a8595095325ab5d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14190/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 964ddf789b022b6958b27d02d7fa54f552de21e9 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14190/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14190/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14190/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14191/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14191/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ff0cb3812d01fadaeedcc25c22ddcc34bcd58cd5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14191/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 964ddf789b022b6958b27d02d7fa54f552de21e9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 964ddf789b022b6958b27d02d7fa54f552de21e9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 964ddf789b022b6958b27d02d7fa54f552de21e9 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14191/instruction.md b/tasks/ohmyzsh__ohmyzsh-14191/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4ec2d8d96f1489ab9ff18d5672182a7ae1f05e07 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14191/instruction.md @@ -0,0 +1,37 @@ +# Issue + +**Title:** fix(extract): preserve .lzma and .Z source files + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- `extract` now runs `unlzma -c` and `uncompress -c` and writes the output to `${file:t:r}`, the same way the `.gz`, `.bz2` and `.xz` cases already do. + - Before, both tools decompressed in place: the source `.lzma` / `.Z` file was deleted even without `-r`, and the output was written next to the source file instead of the current directory or the `-t` target directory. +- Add `plugins/extract/tests/extract.test.zsh`, covering `.lzma` and `.Z` files with the default behaviour, `-t ` and `-r`. + +## Other comments: + +Tested with: + +```sh +zsh -df plugins/extract/tests/extract.test.zsh +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `964ddf789b02`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14191/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14191/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..d893653ba5a3bad58681ec71d23592853e605ec3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14191/solution/patch.diff @@ -0,0 +1,86 @@ +diff --git a/plugins/extract/extract.plugin.zsh b/plugins/extract/extract.plugin.zsh +index 3a576f19..e832ee44 100755 +--- a/plugins/extract/extract.plugin.zsh ++++ b/plugins/extract/extract.plugin.zsh +@@ -107,8 +107,8 @@ EOF + (*.xz) xzcat "$full_path" > "${file:t:r}" ;; + (*.lrz) (( $+commands[lrunzip] )) && lrunzip "$full_path" ;; + (*.lz4) lz4 -d "$full_path" ;; +- (*.lzma) unlzma "$full_path" ;; +- (*.z) uncompress "$full_path" ;; ++ (*.lzma) unlzma -c "$full_path" > "${file:t:r}" ;; ++ (*.z) uncompress -c "$full_path" > "${file:t:r}" ;; + (*.zip|*.war|*.jar|*.ear|*.sublime-package|*.ipa|*.ipsw|*.xpi|*.apk|*.aar|*.whl|*.vsix|*.crx|*.pk3|*.pk4) unzip "$full_path" ;; + (*.rar) + if (( $+commands[unrar] )); then +diff --git a/plugins/extract/tests/extract.test.zsh b/plugins/extract/tests/extract.test.zsh +new file mode 100644 +index 00000000..fe32f978 +--- /dev/null ++++ b/plugins/extract/tests/extract.test.zsh +@@ -0,0 +1,65 @@ ++#!/usr/bin/env zsh ++ ++# Run with: zsh -df plugins/extract/tests/extract.test.zsh ++emulate -L zsh ++setopt err_return ++ ++for tool in lzma unlzma uncompress; do ++ (( $+commands[$tool] )) || { ++ print -u2 -r -- "These tests require $tool." ++ exit 1 ++ } ++done ++ ++source "${0:A:h:h}/extract.plugin.zsh" ++local test_dir=$(mktemp -d) original_dir=$PWD ++ ++check_extract() { ++ local extension=$1 mode=$2 ++ local case_dir="$test_dir/$extension-$mode" ++ mkdir -p "$case_dir/source files" "$case_dir/work/target dir" ++ local archive="$case_dir/source files/sample.txt.$extension" ++ cp "$test_dir/fixture.$extension" "$archive" ++ builtin cd "$case_dir/work" ++ ++ local output="$PWD/sample.txt" ++ local -a args ++ case "$mode" in ++ target) ++ args=(-t 'target dir') ++ output="$PWD/target dir/sample.txt" ++ ;; ++ remove) args=(-r) ;; ++ esac ++ ++ # Run the plugin without the test's ERR_RETURN option. ++ () { ++ emulate -L zsh ++ extract "${args[@]}" "$archive" ++ } || return 1 ++ cmp "$test_dir/plain" "$output" ++ if [[ $mode == remove ]]; then ++ [[ ! -e $archive ]] ++ else ++ [[ -f $archive ]] ++ fi ++ print -r -- "PASS: $extension ($mode)" ++} ++ ++{ ++ print -r -- hello > "$test_dir/plain" ++ lzma -c "$test_dir/plain" > "$test_dir/fixture.lzma" ++ # "hello\n" as a .Z stream, since many systems only ship uncompress. ++ printf '\037\235\220\150\312\260\141\363\106\001' \ ++ > "$test_dir/fixture.Z" ++ ++ for extension in lzma Z; do ++ for mode in default target remove; do ++ check_extract "$extension" "$mode" ++ done ++ done ++ print 'All extract compressed-file tests passed.' ++} always { ++ builtin cd "$original_dir" ++ rm -rf -- "$test_dir" ++} diff --git a/tasks/ohmyzsh__ohmyzsh-14191/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14191/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14191/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14191/task.toml b/tasks/ohmyzsh__ohmyzsh-14191/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..067f1146355b3aa2cb4744cf5c02989251207977 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14191/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14191" +description = "fix(extract): preserve .lzma and .Z source files" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "964ddf789b022b6958b27d02d7fa54f552de21e9" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14191" +source_access = "auto" +built_at = "2026-11-16T16:09:56.860374+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e62c6e6e1e304ddc91368623098641fd9e695682add1129aa9108e52a78b9004" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-20T00:21:39Z" +diff_format = "unified" +context_files = [ + "plugins/extract/extract.plugin.zsh", + "plugins/extract/tests/extract.test.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 69 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.005593+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1d7ecedb3ea5d441072e90d5fb5399a881952ea02abdcb33f024e9913a424a8d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14191/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14191/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14191/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14191/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14191/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4ec2d8d96f1489ab9ff18d5672182a7ae1f05e07 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14191/tests/instruction.md @@ -0,0 +1,37 @@ +# Issue + +**Title:** fix(extract): preserve .lzma and .Z source files + +## Description + +## Standards checklist: + + + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- `extract` now runs `unlzma -c` and `uncompress -c` and writes the output to `${file:t:r}`, the same way the `.gz`, `.bz2` and `.xz` cases already do. + - Before, both tools decompressed in place: the source `.lzma` / `.Z` file was deleted even without `-r`, and the output was written next to the source file instead of the current directory or the `-t` target directory. +- Add `plugins/extract/tests/extract.test.zsh`, covering `.lzma` and `.Z` files with the default behaviour, `-t ` and `-r`. + +## Other comments: + +Tested with: + +```sh +zsh -df plugins/extract/tests/extract.test.zsh +``` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `964ddf789b02`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14191/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14191/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..d893653ba5a3bad58681ec71d23592853e605ec3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14191/tests/oracle.patch @@ -0,0 +1,86 @@ +diff --git a/plugins/extract/extract.plugin.zsh b/plugins/extract/extract.plugin.zsh +index 3a576f19..e832ee44 100755 +--- a/plugins/extract/extract.plugin.zsh ++++ b/plugins/extract/extract.plugin.zsh +@@ -107,8 +107,8 @@ EOF + (*.xz) xzcat "$full_path" > "${file:t:r}" ;; + (*.lrz) (( $+commands[lrunzip] )) && lrunzip "$full_path" ;; + (*.lz4) lz4 -d "$full_path" ;; +- (*.lzma) unlzma "$full_path" ;; +- (*.z) uncompress "$full_path" ;; ++ (*.lzma) unlzma -c "$full_path" > "${file:t:r}" ;; ++ (*.z) uncompress -c "$full_path" > "${file:t:r}" ;; + (*.zip|*.war|*.jar|*.ear|*.sublime-package|*.ipa|*.ipsw|*.xpi|*.apk|*.aar|*.whl|*.vsix|*.crx|*.pk3|*.pk4) unzip "$full_path" ;; + (*.rar) + if (( $+commands[unrar] )); then +diff --git a/plugins/extract/tests/extract.test.zsh b/plugins/extract/tests/extract.test.zsh +new file mode 100644 +index 00000000..fe32f978 +--- /dev/null ++++ b/plugins/extract/tests/extract.test.zsh +@@ -0,0 +1,65 @@ ++#!/usr/bin/env zsh ++ ++# Run with: zsh -df plugins/extract/tests/extract.test.zsh ++emulate -L zsh ++setopt err_return ++ ++for tool in lzma unlzma uncompress; do ++ (( $+commands[$tool] )) || { ++ print -u2 -r -- "These tests require $tool." ++ exit 1 ++ } ++done ++ ++source "${0:A:h:h}/extract.plugin.zsh" ++local test_dir=$(mktemp -d) original_dir=$PWD ++ ++check_extract() { ++ local extension=$1 mode=$2 ++ local case_dir="$test_dir/$extension-$mode" ++ mkdir -p "$case_dir/source files" "$case_dir/work/target dir" ++ local archive="$case_dir/source files/sample.txt.$extension" ++ cp "$test_dir/fixture.$extension" "$archive" ++ builtin cd "$case_dir/work" ++ ++ local output="$PWD/sample.txt" ++ local -a args ++ case "$mode" in ++ target) ++ args=(-t 'target dir') ++ output="$PWD/target dir/sample.txt" ++ ;; ++ remove) args=(-r) ;; ++ esac ++ ++ # Run the plugin without the test's ERR_RETURN option. ++ () { ++ emulate -L zsh ++ extract "${args[@]}" "$archive" ++ } || return 1 ++ cmp "$test_dir/plain" "$output" ++ if [[ $mode == remove ]]; then ++ [[ ! -e $archive ]] ++ else ++ [[ -f $archive ]] ++ fi ++ print -r -- "PASS: $extension ($mode)" ++} ++ ++{ ++ print -r -- hello > "$test_dir/plain" ++ lzma -c "$test_dir/plain" > "$test_dir/fixture.lzma" ++ # "hello\n" as a .Z stream, since many systems only ship uncompress. ++ printf '\037\235\220\150\312\260\141\363\106\001' \ ++ > "$test_dir/fixture.Z" ++ ++ for extension in lzma Z; do ++ for mode in default target remove; do ++ check_extract "$extension" "$mode" ++ done ++ done ++ print 'All extract compressed-file tests passed.' ++} always { ++ builtin cd "$original_dir" ++ rm -rf -- "$test_dir" ++} diff --git a/tasks/ohmyzsh__ohmyzsh-14191/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14191/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7ca4718f25d4b42fa6fd34fe9a8595095325ab5d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14191/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 964ddf789b022b6958b27d02d7fa54f552de21e9 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14191/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14191/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14191/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14193/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14193/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ff0cb3812d01fadaeedcc25c22ddcc34bcd58cd5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14193/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 964ddf789b022b6958b27d02d7fa54f552de21e9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 964ddf789b022b6958b27d02d7fa54f552de21e9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 964ddf789b022b6958b27d02d7fa54f552de21e9 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14193/instruction.md b/tasks/ohmyzsh__ohmyzsh-14193/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..183b1c2570dc817a6292e6c40093d1e842ddefa3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14193/instruction.md @@ -0,0 +1,122 @@ +# Issue + +**Title:** chore(deps): bump the gha-minor group with 3 updates + +## Description + +Bumps the gha-minor group with 3 updates: [actions/create-github-app-token](https://github.com/actions/create-github-app-token), [ossf/scorecard-action](https://github.com/ossf/scorecard-action) and [github/codeql-action/upload-sarif](https://github.com/github/codeql-action). + +Updates `actions/create-github-app-token` from 3.2.0 to 3.3.0 +
          +Release notes +

          Sourced from actions/create-github-app-token's releases.

          +
          +

          v3.3.0

          +

          3.3.0 (2026-10-12)

          +

          Features

          + +

          Bug Fixes

          +
            +
          • deps: bump nested undici from 6.24.0 to 6.29.0 (#403) (12461a3)
          • +
          • deps: bump the production-dependencies group across 1 directory with 3 updates (#395) (a69c19d)
          • +
          +
          +
          +
          +Changelog +

          Sourced from actions/create-github-app-token's changelog.

          +
          +

          Changelog

          +

          3.3.0 (2026-10-12)

          +

          Features

          + +

          Bug Fixes

          +
            +
          • deps: bump nested undici from 6.24.0 to 6.29.0 (#403) (12461a3)
          • +
          • deps: bump the production-dependencies group across 1 directory with 3 updates (#395) (a69c19d)
          • +
          +

          3.2.0 (2026-05-12)

          +

          Features

          +
            +
          • add support for enterprise-level GitHub Apps (#263) (952a2a7)
          • +
          • support full repository names in repositories input (#372) (85eb8dd)
          • +
          +

          Bug Fixes

          +
            +
          • deps: bump @​actions/core from 3.0.0 to 3.0.1 in the production-dependencies group (#364) (43e5c34)
          • +
          • validate private-key input (#376) (f24bbd8)
          • +
          +
          +
          +
          +Commits +
            +
          • 64ab729 chore(main): release 3.3.0 (#402)
          • +
          • f3a828e ci: create signed dist commits in release workflow (#404)
          • +
          • 655017f docs: clarify when owner grants access to all repositories (#378)
          • +
          • 12461a3 fix(deps): bump nested undici from 6.24.0 to 6.29.0 (#403)
          • +
          • a47236f feat: update permission inputs (#399)
          • +
          • a69c19d fix(deps): bump the production-dependencies group across 1 directory with 3 u...
          • +
          • d5cb7ae build(deps): bump actions/checkout from 6 to 7 (#384)
          • +
          • 575da86 build(deps): bump stefanzweifel/git-auto-commit-action from 7.1.0 to 7.2.0 in...
          • +
          • e85f677 test: omit stack traces from snapshots (#401)
          • +
          • 9419396 build(deps-dev): bump c8 from 11.0.0 to 12.0.0 (#400)
          • +
          • Additional commits viewable in compare view
          • +
          +
          +
          + +Updates `ossf/scorecard-action` from 2.4.4 to 2.5.0 +
          +Release notes +

          Sourced from ossf/scorecard-action's releases.

          +
          +

          v2.5.0

          +

          What's Changed

          +

          This release moves the action to Scorecard v5.6.0, the first Scorecard release since its hosted +services moved to new infrastructure.

          +

          For changes to checks and results, and what the infrastructure move means for you, see the +Scorecard v5.6.0 release notes.

          + +

          Other

          + +

          New Contributors

          + +

          Full Changelog: https://github.com/ossf/scorecard-action/compare/v2.4.4...v2.5.0

          +
          +
          +
          +Commits +
            +
          • fa7117d Bump action tag for v2.5.0 release (#1720)
          • +
          • cef4eb5 :seedling: Bump Scorecard to v5.6.0 (#1719)
          • +
          • bedb16e :sparkles: Add intoto results format (#1702)
          • +
          • de70347 Remove the leftover d + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `964ddf789b02`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14193/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14193/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2f5fc9209b4286e1cb948f0817955bb8e3bb904f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14193/solution/patch.diff @@ -0,0 +1,47 @@ +diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml +index 619a6790..b34c0e2f 100644 +--- a/.github/workflows/dependencies.yml ++++ b/.github/workflows/dependencies.yml +@@ -26,7 +26,7 @@ jobs: + fetch-depth: 0 + - name: Authenticate as @ohmyzsh + id: generate-token +- uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 ++ uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + client-id: ${{ secrets.OHMYZSH_CLIENT_ID }} + private-key: ${{ secrets.OHMYZSH_APP_PRIVATE_KEY }} +diff --git a/.github/workflows/project.yml b/.github/workflows/project.yml +index e10b92f2..457829cb 100644 +--- a/.github/workflows/project.yml ++++ b/.github/workflows/project.yml +@@ -22,7 +22,7 @@ jobs: + egress-policy: audit + - name: Authenticate as @ohmyzsh + id: generate-token +- uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 ++ uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + client-id: ${{ secrets.OHMYZSH_CLIENT_ID }} + private-key: ${{ secrets.OHMYZSH_APP_PRIVATE_KEY }} +diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml +index fb9149d8..9271c77a 100644 +--- a/.github/workflows/scorecard.yml ++++ b/.github/workflows/scorecard.yml +@@ -46,7 +46,7 @@ jobs: + persist-credentials: false + + - name: "Run analysis" +- uses: ossf/scorecard-action@2d1146689b8cda280b9bc96326124645441f03bc # v2.4.4 ++ uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.5.0 + with: + results_file: results.sarif + results_format: sarif +@@ -60,6 +60,6 @@ jobs: + retention-days: 5 + + - name: "Upload to code-scanning" +- uses: github/codeql-action/upload-sarif@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3 ++ uses: github/codeql-action/upload-sarif@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0 + with: + sarif_file: results.sarif diff --git a/tasks/ohmyzsh__ohmyzsh-14193/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14193/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14193/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14193/task.toml b/tasks/ohmyzsh__ohmyzsh-14193/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e97a6a2e4eeec01d05759415e9b7ddad309ade60 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14193/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14193" +description = "chore(deps): bump the gha-minor group with 3 updates" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "964ddf789b022b6958b27d02d7fa54f552de21e9" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14193" +source_access = "auto" +built_at = "2026-11-16T16:09:56.856136+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:fd5d5488f3196c0d525e011865ace41daafce908d991e7019596412bdd1e2994" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-20T09:26:43Z" +diff_format = "unified" +context_files = [ + ".github/workflows/dependencies.yml", + ".github/workflows/project.yml", + ".github/workflows/scorecard.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:02.006070+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1d7ecedb3ea5d441072e90d5fb5399a881952ea02abdcb33f024e9913a424a8d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14193/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14193/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14193/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14193/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14193/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..183b1c2570dc817a6292e6c40093d1e842ddefa3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14193/tests/instruction.md @@ -0,0 +1,122 @@ +# Issue + +**Title:** chore(deps): bump the gha-minor group with 3 updates + +## Description + +Bumps the gha-minor group with 3 updates: [actions/create-github-app-token](https://github.com/actions/create-github-app-token), [ossf/scorecard-action](https://github.com/ossf/scorecard-action) and [github/codeql-action/upload-sarif](https://github.com/github/codeql-action). + +Updates `actions/create-github-app-token` from 3.2.0 to 3.3.0 +
            +Release notes +

            Sourced from actions/create-github-app-token's releases.

            +
            +

            v3.3.0

            +

            3.3.0 (2026-10-12)

            +

            Features

            + +

            Bug Fixes

            +
              +
            • deps: bump nested undici from 6.24.0 to 6.29.0 (#403) (12461a3)
            • +
            • deps: bump the production-dependencies group across 1 directory with 3 updates (#395) (a69c19d)
            • +
            +
            +
            +
            +Changelog +

            Sourced from actions/create-github-app-token's changelog.

            +
            +

            Changelog

            +

            3.3.0 (2026-10-12)

            +

            Features

            + +

            Bug Fixes

            +
              +
            • deps: bump nested undici from 6.24.0 to 6.29.0 (#403) (12461a3)
            • +
            • deps: bump the production-dependencies group across 1 directory with 3 updates (#395) (a69c19d)
            • +
            +

            3.2.0 (2026-05-12)

            +

            Features

            +
              +
            • add support for enterprise-level GitHub Apps (#263) (952a2a7)
            • +
            • support full repository names in repositories input (#372) (85eb8dd)
            • +
            +

            Bug Fixes

            +
              +
            • deps: bump @​actions/core from 3.0.0 to 3.0.1 in the production-dependencies group (#364) (43e5c34)
            • +
            • validate private-key input (#376) (f24bbd8)
            • +
            +
            +
            +
            +Commits +
              +
            • 64ab729 chore(main): release 3.3.0 (#402)
            • +
            • f3a828e ci: create signed dist commits in release workflow (#404)
            • +
            • 655017f docs: clarify when owner grants access to all repositories (#378)
            • +
            • 12461a3 fix(deps): bump nested undici from 6.24.0 to 6.29.0 (#403)
            • +
            • a47236f feat: update permission inputs (#399)
            • +
            • a69c19d fix(deps): bump the production-dependencies group across 1 directory with 3 u...
            • +
            • d5cb7ae build(deps): bump actions/checkout from 6 to 7 (#384)
            • +
            • 575da86 build(deps): bump stefanzweifel/git-auto-commit-action from 7.1.0 to 7.2.0 in...
            • +
            • e85f677 test: omit stack traces from snapshots (#401)
            • +
            • 9419396 build(deps-dev): bump c8 from 11.0.0 to 12.0.0 (#400)
            • +
            • Additional commits viewable in compare view
            • +
            +
            +
            + +Updates `ossf/scorecard-action` from 2.4.4 to 2.5.0 +
            +Release notes +

            Sourced from ossf/scorecard-action's releases.

            +
            +

            v2.5.0

            +

            What's Changed

            +

            This release moves the action to Scorecard v5.6.0, the first Scorecard release since its hosted +services moved to new infrastructure.

            +

            For changes to checks and results, and what the infrastructure move means for you, see the +Scorecard v5.6.0 release notes.

            + +

            Other

            + +

            New Contributors

            + +

            Full Changelog: https://github.com/ossf/scorecard-action/compare/v2.4.4...v2.5.0

            +
            +
            +
            +Commits +
              +
            • fa7117d Bump action tag for v2.5.0 release (#1720)
            • +
            • cef4eb5 :seedling: Bump Scorecard to v5.6.0 (#1719)
            • +
            • bedb16e :sparkles: Add intoto results format (#1702)
            • +
            • de70347 Remove the leftover d + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `964ddf789b02`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14193/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14193/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2f5fc9209b4286e1cb948f0817955bb8e3bb904f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14193/tests/oracle.patch @@ -0,0 +1,47 @@ +diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml +index 619a6790..b34c0e2f 100644 +--- a/.github/workflows/dependencies.yml ++++ b/.github/workflows/dependencies.yml +@@ -26,7 +26,7 @@ jobs: + fetch-depth: 0 + - name: Authenticate as @ohmyzsh + id: generate-token +- uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 ++ uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + client-id: ${{ secrets.OHMYZSH_CLIENT_ID }} + private-key: ${{ secrets.OHMYZSH_APP_PRIVATE_KEY }} +diff --git a/.github/workflows/project.yml b/.github/workflows/project.yml +index e10b92f2..457829cb 100644 +--- a/.github/workflows/project.yml ++++ b/.github/workflows/project.yml +@@ -22,7 +22,7 @@ jobs: + egress-policy: audit + - name: Authenticate as @ohmyzsh + id: generate-token +- uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0 ++ uses: actions/create-github-app-token@64ab729a6294000f5aa4a4bc0b73d1f32bc45510 # v3.3.0 + with: + client-id: ${{ secrets.OHMYZSH_CLIENT_ID }} + private-key: ${{ secrets.OHMYZSH_APP_PRIVATE_KEY }} +diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml +index fb9149d8..9271c77a 100644 +--- a/.github/workflows/scorecard.yml ++++ b/.github/workflows/scorecard.yml +@@ -46,7 +46,7 @@ jobs: + persist-credentials: false + + - name: "Run analysis" +- uses: ossf/scorecard-action@2d1146689b8cda280b9bc96326124645441f03bc # v2.4.4 ++ uses: ossf/scorecard-action@fa7117db83c52d787ae5a89f350999701505d78e # v2.5.0 + with: + results_file: results.sarif + results_format: sarif +@@ -60,6 +60,6 @@ jobs: + retention-days: 5 + + - name: "Upload to code-scanning" +- uses: github/codeql-action/upload-sarif@24c54180a607b1449ed407dd24f251e4e9147c8d # v4.38.3 ++ uses: github/codeql-action/upload-sarif@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0 + with: + sarif_file: results.sarif diff --git a/tasks/ohmyzsh__ohmyzsh-14193/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14193/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7ca4718f25d4b42fa6fd34fe9a8595095325ab5d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14193/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 964ddf789b022b6958b27d02d7fa54f552de21e9 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14193/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14193/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14193/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14197/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14197/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4587f5bd166c944c998be9b8536d1ca91d1c6048 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14197/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 0650a250405af1e480b1ecf8c33bc960b9f333f5 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 0650a250405af1e480b1ecf8c33bc960b9f333f5 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 0650a250405af1e480b1ecf8c33bc960b9f333f5 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14197/instruction.md b/tasks/ohmyzsh__ohmyzsh-14197/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6fddcf0db9c404718e88d2cb0bc43a0447c614ca --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14197/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** feat(bridgetown): update aliases for current CLI + +## Description + +## Summary + +- add aliases for current Bridgetown commands and standard project tasks +- remove the obsolete `doctor` alias +- run plugin commands through the project binstub +- document each alias and clarify global versus project-scoped usage + +## Testing + +- verified commands against Bridgetown 2.2.2 +- ran `zsh -n plugins/bridgetown/bridgetown.plugin.zsh` +- checked alias definitions in a clean Zsh session +- ran `git diff --check` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0650a250405a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14197/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14197/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..042efd4a7201ea2e86f72b9ae3e4987c6c84bec4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14197/solution/patch.diff @@ -0,0 +1,75 @@ +diff --git a/plugins/bridgetown/README.md b/plugins/bridgetown/README.md +index 0a41814e..7f8a8eab 100644 +--- a/plugins/bridgetown/README.md ++++ b/plugins/bridgetown/README.md +@@ -1,6 +1,6 @@ + # Bridgetown plugin + +-This plugin adds some aliases and autocompletion for common [Bridgetown](https://bridgetownrb.com/) commands. ++This plugin adds aliases for common [Bridgetown](https://www.bridgetownrb.com/) commands. + + To use it, add `bridgetown` to the plugins array in your zshrc file: + +@@ -10,17 +10,27 @@ plugins=(... bridgetown) + + ## Aliases + +-| Alias | Command | +-|-------|----------------------------| +-| br | `bridgetown` | +-| bra | `bin/bridgetown apply` | +-| brb | `bin/bridgetown build` | +-| brc | `bin/bridgetown console` | +-| brclean | `bin/bridgetown clean` | +-| brd | `bin/bridgetown deploy` | +-| brdoc | `bin/bridgetown doctor` | +-| brh | `bin/bridgetown help` | +-| brn | `bridgetown new` | +-| brp | `bridgetown plugins` | +-| brpl | `bridgetown plugins list` | +-| brs | `bin/bridgetown start` | ++Most aliases use the project's `bin/bridgetown` executable so the command runs with the Bridgetown version ++locked in its `Gemfile`. The `br` and `brn` aliases use the globally installed executable and can be run ++outside a Bridgetown project. ++ ++| Alias | Command | Description | ++| --------- | ---------------------------- | ---------------------------------------- | ++| `br` | `bridgetown` | Run the globally installed CLI | ++| `bra` | `bin/bridgetown apply` | Apply an automation | ++| `brb` | `bin/bridgetown build` | Build the site | ++| `brc` | `bin/bridgetown console` | Open the Bridgetown console | ++| `brclean` | `bin/bridgetown clean` | Remove generated files and caches | ++| `brco` | `bin/bridgetown configure` | Apply a bundled configuration | ++| `brd` | `bin/bridgetown deploy` | Run the project's deployment task | ++| `brdev` | `bin/bridgetown dev` | Start the development server | ++| `bre` | `bin/bridgetown esbuild` | Manage the esbuild configuration | ++| `brh` | `bin/bridgetown help` | Show command help | ++| `brn` | `bridgetown new` | Create a new Bridgetown site | ++| `brp` | `bin/bridgetown plugins` | Access plugin commands | ++| `brpl` | `bin/bridgetown plugins list` | List installed plugins | ++| `brs` | `bin/bridgetown start` | Start the development server | ++| `brt` | `bin/bridgetown test` | Run the project's test build task | ++ ++`deploy` and `test` are standard tasks from the `Rakefile` generated for a new Bridgetown site. If the project ++customizes or removes those tasks, the corresponding aliases follow that project behavior. +diff --git a/plugins/bridgetown/bridgetown.plugin.zsh b/plugins/bridgetown/bridgetown.plugin.zsh +index 502e9dfe..2228bb74 100644 +--- a/plugins/bridgetown/bridgetown.plugin.zsh ++++ b/plugins/bridgetown/bridgetown.plugin.zsh +@@ -3,10 +3,13 @@ alias bra='bin/bridgetown apply' + alias brb='bin/bridgetown build' + alias brc='bin/bridgetown console' + alias brclean='bin/bridgetown clean' ++alias brco='bin/bridgetown configure' + alias brd='bin/bridgetown deploy' +-alias brdoc='bin/bridgetown doctor' ++alias brdev='bin/bridgetown dev' ++alias bre='bin/bridgetown esbuild' + alias brh='bin/bridgetown help' + alias brn='bridgetown new' +-alias brp='bridgetown plugins' +-alias brpl='bridgetown plugins list' ++alias brp='bin/bridgetown plugins' ++alias brpl='bin/bridgetown plugins list' + alias brs='bin/bridgetown start' ++alias brt='bin/bridgetown test' diff --git a/tasks/ohmyzsh__ohmyzsh-14197/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14197/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14197/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14197/task.toml b/tasks/ohmyzsh__ohmyzsh-14197/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fb8696900969530fc6b7804c3f0bf3a727cf5c07 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14197/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14197" +description = "feat(bridgetown): update aliases for current CLI" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "0650a250405af1e480b1ecf8c33bc960b9f333f5" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14197" +source_access = "auto" +built_at = "2026-11-16T16:09:56.853420+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:06267baf4877c75d8b384357b7f9044d4425a52d184c462c0f49be0c61d68562" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-21T10:31:15Z" +diff_format = "unified" +context_files = [ + "plugins/bridgetown/README.md", + "plugins/bridgetown/bridgetown.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 49 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.006590+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6875ac785122996d99f8da0a5e06d42124cc7e628f6ea3e3afc641576726feb1" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14197/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14197/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14197/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14197/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14197/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6fddcf0db9c404718e88d2cb0bc43a0447c614ca --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14197/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** feat(bridgetown): update aliases for current CLI + +## Description + +## Summary + +- add aliases for current Bridgetown commands and standard project tasks +- remove the obsolete `doctor` alias +- run plugin commands through the project binstub +- document each alias and clarify global versus project-scoped usage + +## Testing + +- verified commands against Bridgetown 2.2.2 +- ran `zsh -n plugins/bridgetown/bridgetown.plugin.zsh` +- checked alias definitions in a clean Zsh session +- ran `git diff --check` + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0650a250405a`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14197/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14197/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..042efd4a7201ea2e86f72b9ae3e4987c6c84bec4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14197/tests/oracle.patch @@ -0,0 +1,75 @@ +diff --git a/plugins/bridgetown/README.md b/plugins/bridgetown/README.md +index 0a41814e..7f8a8eab 100644 +--- a/plugins/bridgetown/README.md ++++ b/plugins/bridgetown/README.md +@@ -1,6 +1,6 @@ + # Bridgetown plugin + +-This plugin adds some aliases and autocompletion for common [Bridgetown](https://bridgetownrb.com/) commands. ++This plugin adds aliases for common [Bridgetown](https://www.bridgetownrb.com/) commands. + + To use it, add `bridgetown` to the plugins array in your zshrc file: + +@@ -10,17 +10,27 @@ plugins=(... bridgetown) + + ## Aliases + +-| Alias | Command | +-|-------|----------------------------| +-| br | `bridgetown` | +-| bra | `bin/bridgetown apply` | +-| brb | `bin/bridgetown build` | +-| brc | `bin/bridgetown console` | +-| brclean | `bin/bridgetown clean` | +-| brd | `bin/bridgetown deploy` | +-| brdoc | `bin/bridgetown doctor` | +-| brh | `bin/bridgetown help` | +-| brn | `bridgetown new` | +-| brp | `bridgetown plugins` | +-| brpl | `bridgetown plugins list` | +-| brs | `bin/bridgetown start` | ++Most aliases use the project's `bin/bridgetown` executable so the command runs with the Bridgetown version ++locked in its `Gemfile`. The `br` and `brn` aliases use the globally installed executable and can be run ++outside a Bridgetown project. ++ ++| Alias | Command | Description | ++| --------- | ---------------------------- | ---------------------------------------- | ++| `br` | `bridgetown` | Run the globally installed CLI | ++| `bra` | `bin/bridgetown apply` | Apply an automation | ++| `brb` | `bin/bridgetown build` | Build the site | ++| `brc` | `bin/bridgetown console` | Open the Bridgetown console | ++| `brclean` | `bin/bridgetown clean` | Remove generated files and caches | ++| `brco` | `bin/bridgetown configure` | Apply a bundled configuration | ++| `brd` | `bin/bridgetown deploy` | Run the project's deployment task | ++| `brdev` | `bin/bridgetown dev` | Start the development server | ++| `bre` | `bin/bridgetown esbuild` | Manage the esbuild configuration | ++| `brh` | `bin/bridgetown help` | Show command help | ++| `brn` | `bridgetown new` | Create a new Bridgetown site | ++| `brp` | `bin/bridgetown plugins` | Access plugin commands | ++| `brpl` | `bin/bridgetown plugins list` | List installed plugins | ++| `brs` | `bin/bridgetown start` | Start the development server | ++| `brt` | `bin/bridgetown test` | Run the project's test build task | ++ ++`deploy` and `test` are standard tasks from the `Rakefile` generated for a new Bridgetown site. If the project ++customizes or removes those tasks, the corresponding aliases follow that project behavior. +diff --git a/plugins/bridgetown/bridgetown.plugin.zsh b/plugins/bridgetown/bridgetown.plugin.zsh +index 502e9dfe..2228bb74 100644 +--- a/plugins/bridgetown/bridgetown.plugin.zsh ++++ b/plugins/bridgetown/bridgetown.plugin.zsh +@@ -3,10 +3,13 @@ alias bra='bin/bridgetown apply' + alias brb='bin/bridgetown build' + alias brc='bin/bridgetown console' + alias brclean='bin/bridgetown clean' ++alias brco='bin/bridgetown configure' + alias brd='bin/bridgetown deploy' +-alias brdoc='bin/bridgetown doctor' ++alias brdev='bin/bridgetown dev' ++alias bre='bin/bridgetown esbuild' + alias brh='bin/bridgetown help' + alias brn='bridgetown new' +-alias brp='bridgetown plugins' +-alias brpl='bridgetown plugins list' ++alias brp='bin/bridgetown plugins' ++alias brpl='bin/bridgetown plugins list' + alias brs='bin/bridgetown start' ++alias brt='bin/bridgetown test' diff --git a/tasks/ohmyzsh__ohmyzsh-14197/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14197/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..9f41c7b3b071c05b857696c59825b5f0054ab3d1 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14197/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 0650a250405af1e480b1ecf8c33bc960b9f333f5 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14197/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14197/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14197/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14213/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14213/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..95bb83865c24770e3b9cf8da886152b8838f5eb9 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14213/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 2100c630ba4bd67bb48802c3e7da893a4fdaa1a0 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 2100c630ba4bd67bb48802c3e7da893a4fdaa1a0 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 2100c630ba4bd67bb48802c3e7da893a4fdaa1a0 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14213/instruction.md b/tasks/ohmyzsh__ohmyzsh-14213/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f7f8fc1f9c13cfecae2d99a6d3043f5b9035007e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14213/instruction.md @@ -0,0 +1,121 @@ +# Issue + +**Title:** chore(deps): bump the gha-minor group with 3 updates + +## Description + +Bumps the gha-minor group with 3 updates: [step-security/harden-runner](https://github.com/step-security/harden-runner), [actions/setup-python](https://github.com/actions/setup-python) and [github/codeql-action/upload-sarif](https://github.com/github/codeql-action). + +Updates `step-security/harden-runner` from 2.22.1 to 2.22.2 +
              +Release notes +

              Sourced from step-security/harden-runner's releases.

              +
              +

              v2.22.2

              +

              What's Changed

              +
                +
              • Fixed inbound (ingress) network traffic being incorrectly classified as outbound (egress) traffic on macOS
              • +
              • Fixed implicit endpoints intended for self-hosted runners being applied to custom VM environments on Linux (enterprise tier)
              • +
              • Improved network and DNS tracing, enforcement logic, and process information correlation on Linux (enterprise tier)
              • +
              +

              Full Changelog: https://github.com/step-security/harden-runner/compare/v2.22.1...v2.22.2

              +
              +
              +
              +Commits +
                +
              • dc2769a Merge pull request #707 from step-security/rc-45
              • +
              • ab0b273 Merge pull request #706 from h0x0er/rc-45
              • +
              • 03ccff8 Remove agent-preinstalled skip for third-party runners
              • +
              • 815e48d Skip agent install and post-step cleanup when agent is already installed
              • +
              • See full diff in compare view
              • +
              +
              +
              + +Updates `actions/setup-python` from 7.0.0 to 7.1.0 +
              +Release notes +

              Sourced from actions/setup-python's releases.

              +
              +

              v7.1.0

              +

              What's Changed

              +

              Enhancements

              + +

              Dependency Upgrade

              + +

              New Contributors

              + +

              Full Changelog: https://github.com/actions/setup-python/compare/v7.0.0...v7.1.0

              +
              +
              +
              +Commits +
                +
              • 6d4fd22 Cache upgrade to 6.3.0 (#1370)
              • +
              • ec52d0a Bump @​typescript-eslint/eslint-plugin from 8.62.0 to 8.71.1 (#1369)
              • +
              • ff73b24 Bump prettier from 3.8.4 to 3.9.9 and package.json from 7.0.0 to 7.1.0 (#1363)
              • +
              • 0e40890 Bump brace-expansion from 5.0.9 to 5.0.12 (#1365)
              • +
              • 3892123 Bump ts-jest from 29.4.11 to 29.4.14 (#1361)
              • +
              • 6609657 Bump undici from 6.28.0 to 6.29.0 (#1364)
              • +
              • e1be392 Bump @​types/semver from 7.7.1 to 7.8.0 (#1359)
              • +
              • 06da627 Bump @​vercel/ncc from 0.44.0 to 0.45.0 (#1357)
              • +
              • af9bcc7 Bump eslint-plugin-jest from 29.15.2 to 29.16.6 (#1342)
              • +
              • 7aeabeb Bump @​typescript-eslint/parser from 8.62.0 to 8.70.0 (#1343)
              • +
              • Additional commits viewable in compare view
              • +
              +
              +
              + +Updates `github/codeql-action/upload-sarif` from 4.39.0 to 4.39.1 +
              +Release notes +

              Sourced from github/codeql-action/upload-sarif's releases.

              +
              +

              v4.39.1

              +
                +
              • Update default CodeQL bundle version to 2.27.3. #4256
              • +
              +
              +
              +
              +Changelog +

              Sourced from github/codeql-action/upload-sarif's changelog.

              +
              +

              CodeQL Action Changelog

              +

              See the releases page for the relevant changes to the CodeQL CLI and language packs.

              +

              [UNRELEASED]

              +

              No user facing changes.

              +

              4.39.1 - 21 Oct 2026

              +
                +
              • Update default CodeQL bundle version to 2.27.3. #4256
              • +
              +

              4.39.0 - 15 Oct 2026

              +
                +
              • Breaking change: Bump the minimum required CodeQL bundle version to 2.20.7. #4205
              • +
              • The codeql-action/analyze step now validates that a correct argument for the checkout_path input has been provided. The checkout_path input must be set to the path where the repository that is being analyzed is checked out at on the runner, if that path is something other than the workspace root. If the path does not point to a repository checkout or is different from the path that was used by codeql-action/init, then the CodeQL Action now produces a warning. #4148
              • +
              • Resolved an issue with third-party caching implement + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2100c630ba4b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14213/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14213/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4f3f36ed3648c815041e156991459f52099d9901 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14213/solution/patch.diff @@ -0,0 +1,91 @@ +diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml +index b34c0e2f..7a382aae 100644 +--- a/.github/workflows/dependencies.yml ++++ b/.github/workflows/dependencies.yml +@@ -16,7 +16,7 @@ jobs: + contents: write # this is needed to push commits and branches + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 ++ uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 + with: + egress-policy: audit + +@@ -31,7 +31,7 @@ jobs: + client-id: ${{ secrets.OHMYZSH_CLIENT_ID }} + private-key: ${{ secrets.OHMYZSH_APP_PRIVATE_KEY }} + - name: Setup Python +- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 ++ uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + cache: "pip" +diff --git a/.github/workflows/installer.yml b/.github/workflows/installer.yml +index a69bc3c7..88f10b0b 100644 +--- a/.github/workflows/installer.yml ++++ b/.github/workflows/installer.yml +@@ -26,7 +26,7 @@ jobs: + - macos-latest + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 ++ uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 + with: + egress-policy: audit + +@@ -47,7 +47,7 @@ jobs: + - test + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 ++ uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 + with: + egress-policy: audit + +diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml +index 6d5b6c5a..cedfd03b 100644 +--- a/.github/workflows/main.yml ++++ b/.github/workflows/main.yml +@@ -24,7 +24,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 ++ uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 + with: + egress-policy: audit + +diff --git a/.github/workflows/project.yml b/.github/workflows/project.yml +index 457829cb..8cbf0667 100644 +--- a/.github/workflows/project.yml ++++ b/.github/workflows/project.yml +@@ -17,7 +17,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 ++ uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 + with: + egress-policy: audit + - name: Authenticate as @ohmyzsh +diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml +index 9271c77a..e07679e3 100644 +--- a/.github/workflows/scorecard.yml ++++ b/.github/workflows/scorecard.yml +@@ -36,7 +36,7 @@ jobs: + + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 ++ uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 + with: + egress-policy: audit + +@@ -60,6 +60,6 @@ jobs: + retention-days: 5 + + - name: "Upload to code-scanning" +- uses: github/codeql-action/upload-sarif@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0 ++ uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1 + with: + sarif_file: results.sarif diff --git a/tasks/ohmyzsh__ohmyzsh-14213/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14213/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14213/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14213/task.toml b/tasks/ohmyzsh__ohmyzsh-14213/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..358bb08382c3e10ea37ed9b67d01abfb054fbb93 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14213/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14213" +description = "chore(deps): bump the gha-minor group with 3 updates" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "2100c630ba4bd67bb48802c3e7da893a4fdaa1a0" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14213" +source_access = "auto" +built_at = "2026-11-16T16:09:56.850816+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:739490ce48d70e5bef32bfb9b5aac4d33eb0c8878a0d21eaf14a3660a62141e0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-25T14:38:35Z" +diff_format = "unified" +context_files = [ + ".github/workflows/dependencies.yml", + ".github/workflows/installer.yml", + ".github/workflows/main.yml", + ".github/workflows/project.yml", + ".github/workflows/scorecard.yml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 16 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.007129+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3e3f9608ee6280ca1775c3634625e965de3493a0da213770ac0806d497f27178" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14213/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14213/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14213/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14213/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14213/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f7f8fc1f9c13cfecae2d99a6d3043f5b9035007e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14213/tests/instruction.md @@ -0,0 +1,121 @@ +# Issue + +**Title:** chore(deps): bump the gha-minor group with 3 updates + +## Description + +Bumps the gha-minor group with 3 updates: [step-security/harden-runner](https://github.com/step-security/harden-runner), [actions/setup-python](https://github.com/actions/setup-python) and [github/codeql-action/upload-sarif](https://github.com/github/codeql-action). + +Updates `step-security/harden-runner` from 2.22.1 to 2.22.2 +
                +Release notes +

                Sourced from step-security/harden-runner's releases.

                +
                +

                v2.22.2

                +

                What's Changed

                +
                  +
                • Fixed inbound (ingress) network traffic being incorrectly classified as outbound (egress) traffic on macOS
                • +
                • Fixed implicit endpoints intended for self-hosted runners being applied to custom VM environments on Linux (enterprise tier)
                • +
                • Improved network and DNS tracing, enforcement logic, and process information correlation on Linux (enterprise tier)
                • +
                +

                Full Changelog: https://github.com/step-security/harden-runner/compare/v2.22.1...v2.22.2

                +
                +
                +
                +Commits +
                  +
                • dc2769a Merge pull request #707 from step-security/rc-45
                • +
                • ab0b273 Merge pull request #706 from h0x0er/rc-45
                • +
                • 03ccff8 Remove agent-preinstalled skip for third-party runners
                • +
                • 815e48d Skip agent install and post-step cleanup when agent is already installed
                • +
                • See full diff in compare view
                • +
                +
                +
                + +Updates `actions/setup-python` from 7.0.0 to 7.1.0 +
                +Release notes +

                Sourced from actions/setup-python's releases.

                +
                +

                v7.1.0

                +

                What's Changed

                +

                Enhancements

                + +

                Dependency Upgrade

                + +

                New Contributors

                + +

                Full Changelog: https://github.com/actions/setup-python/compare/v7.0.0...v7.1.0

                +
                +
                +
                +Commits +
                  +
                • 6d4fd22 Cache upgrade to 6.3.0 (#1370)
                • +
                • ec52d0a Bump @​typescript-eslint/eslint-plugin from 8.62.0 to 8.71.1 (#1369)
                • +
                • ff73b24 Bump prettier from 3.8.4 to 3.9.9 and package.json from 7.0.0 to 7.1.0 (#1363)
                • +
                • 0e40890 Bump brace-expansion from 5.0.9 to 5.0.12 (#1365)
                • +
                • 3892123 Bump ts-jest from 29.4.11 to 29.4.14 (#1361)
                • +
                • 6609657 Bump undici from 6.28.0 to 6.29.0 (#1364)
                • +
                • e1be392 Bump @​types/semver from 7.7.1 to 7.8.0 (#1359)
                • +
                • 06da627 Bump @​vercel/ncc from 0.44.0 to 0.45.0 (#1357)
                • +
                • af9bcc7 Bump eslint-plugin-jest from 29.15.2 to 29.16.6 (#1342)
                • +
                • 7aeabeb Bump @​typescript-eslint/parser from 8.62.0 to 8.70.0 (#1343)
                • +
                • Additional commits viewable in compare view
                • +
                +
                +
                + +Updates `github/codeql-action/upload-sarif` from 4.39.0 to 4.39.1 +
                +Release notes +

                Sourced from github/codeql-action/upload-sarif's releases.

                +
                +

                v4.39.1

                +
                  +
                • Update default CodeQL bundle version to 2.27.3. #4256
                • +
                +
                +
                +
                +Changelog +

                Sourced from github/codeql-action/upload-sarif's changelog.

                +
                +

                CodeQL Action Changelog

                +

                See the releases page for the relevant changes to the CodeQL CLI and language packs.

                +

                [UNRELEASED]

                +

                No user facing changes.

                +

                4.39.1 - 21 Oct 2026

                +
                  +
                • Update default CodeQL bundle version to 2.27.3. #4256
                • +
                +

                4.39.0 - 15 Oct 2026

                +
                  +
                • Breaking change: Bump the minimum required CodeQL bundle version to 2.20.7. #4205
                • +
                • The codeql-action/analyze step now validates that a correct argument for the checkout_path input has been provided. The checkout_path input must be set to the path where the repository that is being analyzed is checked out at on the runner, if that path is something other than the workspace root. If the path does not point to a repository checkout or is different from the path that was used by codeql-action/init, then the CodeQL Action now produces a warning. #4148
                • +
                • Resolved an issue with third-party caching implement + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `2100c630ba4b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14213/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14213/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4f3f36ed3648c815041e156991459f52099d9901 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14213/tests/oracle.patch @@ -0,0 +1,91 @@ +diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml +index b34c0e2f..7a382aae 100644 +--- a/.github/workflows/dependencies.yml ++++ b/.github/workflows/dependencies.yml +@@ -16,7 +16,7 @@ jobs: + contents: write # this is needed to push commits and branches + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 ++ uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 + with: + egress-policy: audit + +@@ -31,7 +31,7 @@ jobs: + client-id: ${{ secrets.OHMYZSH_CLIENT_ID }} + private-key: ${{ secrets.OHMYZSH_APP_PRIVATE_KEY }} + - name: Setup Python +- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 ++ uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0 + with: + python-version: "3.12" + cache: "pip" +diff --git a/.github/workflows/installer.yml b/.github/workflows/installer.yml +index a69bc3c7..88f10b0b 100644 +--- a/.github/workflows/installer.yml ++++ b/.github/workflows/installer.yml +@@ -26,7 +26,7 @@ jobs: + - macos-latest + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 ++ uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 + with: + egress-policy: audit + +@@ -47,7 +47,7 @@ jobs: + - test + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 ++ uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 + with: + egress-policy: audit + +diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml +index 6d5b6c5a..cedfd03b 100644 +--- a/.github/workflows/main.yml ++++ b/.github/workflows/main.yml +@@ -24,7 +24,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 ++ uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 + with: + egress-policy: audit + +diff --git a/.github/workflows/project.yml b/.github/workflows/project.yml +index 457829cb..8cbf0667 100644 +--- a/.github/workflows/project.yml ++++ b/.github/workflows/project.yml +@@ -17,7 +17,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 ++ uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 + with: + egress-policy: audit + - name: Authenticate as @ohmyzsh +diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml +index 9271c77a..e07679e3 100644 +--- a/.github/workflows/scorecard.yml ++++ b/.github/workflows/scorecard.yml +@@ -36,7 +36,7 @@ jobs: + + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@ccd8616d44fd3846e67624a50d5aad6d37bf2d25 # v2.22.1 ++ uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 + with: + egress-policy: audit + +@@ -60,6 +60,6 @@ jobs: + retention-days: 5 + + - name: "Upload to code-scanning" +- uses: github/codeql-action/upload-sarif@6f2ac81f5cd81fe351a197ba0b00d91d03cd2aee # v4.39.0 ++ uses: github/codeql-action/upload-sarif@9b3254085494b55a0f7c4c2b3d2d52cc712ce370 # v4.39.1 + with: + sarif_file: results.sarif diff --git a/tasks/ohmyzsh__ohmyzsh-14213/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14213/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..a266a04026d5ce8716ceaf3dfed819f7411fc710 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14213/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 2100c630ba4bd67bb48802c3e7da893a4fdaa1a0 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14213/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14213/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14213/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14216/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14216/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5cb006607e9a3533f747ae040eaa185bfb0409c9 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14216/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d2b7f557cceaddb16ba89bbf8200d8a8df35c4d8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d2b7f557cceaddb16ba89bbf8200d8a8df35c4d8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d2b7f557cceaddb16ba89bbf8200d8a8df35c4d8 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14216/instruction.md b/tasks/ohmyzsh__ohmyzsh-14216/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d428c8746a41350e3ad605cf7ca76652f760e7b7 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14216/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** fix(clipboard): strip PowerShell carriage returns on WSL + +## Description + +. + +`powershell.exe Get-Clipboard` emits CRLF under WSL. The vi-mode paste widget captures `clippaste` with command substitution, which strips the trailing LF but leaves CR in the cut buffer. As a result, `xp` can insert `^M` into the command line. Strip carriage returns in the Windows clipboard branch and add a regression test for multiline output. + +### Tests + +- `zsh -df lib/tests/clipboard.test.zsh` +- `zsh -n lib/clipboard.zsh lib/tests/clipboard.test.zsh` +- On Windows 11 with Ubuntu 24.04 under WSL 1 and zsh 5.9, captured the ZLE buffer after `Esc`, `x`, `p`: `echo abc\r` before the fix, `echo abc` after it. + +I could not run the WSL 2 interaction test in this VM: Windows bugchecked when starting the distribution, before zsh loaded. The WSL 1 test exercised the same `clip.exe`/`powershell.exe` branch. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d2b7f557ccea`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14216/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14216/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..0a4ec93a463a2b3f44b87304e428c41b8cd4cbfa --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14216/solution/patch.diff @@ -0,0 +1,16 @@ +diff --git a/lib/clipboard.zsh b/lib/clipboard.zsh +index 27e81525..c9306b0f 100644 +--- a/lib/clipboard.zsh ++++ b/lib/clipboard.zsh +@@ -59,7 +59,10 @@ function detect-clipboard() { + function clippaste() { cat /dev/clipboard; } + elif (( $+commands[clip.exe] )) && (( $+commands[powershell.exe] )); then + function clipcopy() { cat "${1:-/dev/stdin}" | clip.exe; } +- function clippaste() { powershell.exe -noprofile -command Get-Clipboard; } ++ function clippaste() { ++ setopt localoptions pipefail ++ powershell.exe -noprofile -command Get-Clipboard | tr -d '\r' ++ } + elif [ -n "${WAYLAND_DISPLAY:-}" ] && (( ${+commands[wl-copy]} )) && (( ${+commands[wl-paste]} )); then + function clipcopy() { cat "${1:-/dev/stdin}" | wl-copy &>/dev/null &|; } + function clippaste() { wl-paste --no-newline; } diff --git a/tasks/ohmyzsh__ohmyzsh-14216/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14216/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14216/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14216/task.toml b/tasks/ohmyzsh__ohmyzsh-14216/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..023d02c3b09b8faf362a18cc97f27c5c552ee8cc --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14216/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14216" +description = "fix(clipboard): strip PowerShell carriage returns on WSL" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "d2b7f557cceaddb16ba89bbf8200d8a8df35c4d8" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14216" +source_access = "auto" +built_at = "2026-11-16T16:09:56.847991+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:64a383076f93250caa484ad52e4e66866cce0dea1aa1e129fba26e806d582c7b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-10-27T11:37:50Z" +diff_format = "unified" +context_files = [ + "lib/clipboard.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.007658+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:3e6ed77e54717f35d6a7b64b4c77a05c53c01e825f6c90597d93da60551fa401" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14216/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14216/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14216/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14216/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14216/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d428c8746a41350e3ad605cf7ca76652f760e7b7 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14216/tests/instruction.md @@ -0,0 +1,21 @@ +# Issue + +**Title:** fix(clipboard): strip PowerShell carriage returns on WSL + +## Description + +. + +`powershell.exe Get-Clipboard` emits CRLF under WSL. The vi-mode paste widget captures `clippaste` with command substitution, which strips the trailing LF but leaves CR in the cut buffer. As a result, `xp` can insert `^M` into the command line. Strip carriage returns in the Windows clipboard branch and add a regression test for multiline output. + +### Tests + +- `zsh -df lib/tests/clipboard.test.zsh` +- `zsh -n lib/clipboard.zsh lib/tests/clipboard.test.zsh` +- On Windows 11 with Ubuntu 24.04 under WSL 1 and zsh 5.9, captured the ZLE buffer after `Esc`, `x`, `p`: `echo abc\r` before the fix, `echo abc` after it. + +I could not run the WSL 2 interaction test in this VM: Windows bugchecked when starting the distribution, before zsh loaded. The WSL 1 test exercised the same `clip.exe`/`powershell.exe` branch. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d2b7f557ccea`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14216/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14216/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..0a4ec93a463a2b3f44b87304e428c41b8cd4cbfa --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14216/tests/oracle.patch @@ -0,0 +1,16 @@ +diff --git a/lib/clipboard.zsh b/lib/clipboard.zsh +index 27e81525..c9306b0f 100644 +--- a/lib/clipboard.zsh ++++ b/lib/clipboard.zsh +@@ -59,7 +59,10 @@ function detect-clipboard() { + function clippaste() { cat /dev/clipboard; } + elif (( $+commands[clip.exe] )) && (( $+commands[powershell.exe] )); then + function clipcopy() { cat "${1:-/dev/stdin}" | clip.exe; } +- function clippaste() { powershell.exe -noprofile -command Get-Clipboard; } ++ function clippaste() { ++ setopt localoptions pipefail ++ powershell.exe -noprofile -command Get-Clipboard | tr -d '\r' ++ } + elif [ -n "${WAYLAND_DISPLAY:-}" ] && (( ${+commands[wl-copy]} )) && (( ${+commands[wl-paste]} )); then + function clipcopy() { cat "${1:-/dev/stdin}" | wl-copy &>/dev/null &|; } + function clippaste() { wl-paste --no-newline; } diff --git a/tasks/ohmyzsh__ohmyzsh-14216/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14216/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..d5641803bcf1590e377a3f8d8523c22f0a87a494 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14216/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d2b7f557cceaddb16ba89bbf8200d8a8df35c4d8 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14216/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14216/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14216/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14238/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14238/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d88e050ea2885f10e9157112431c746ea54d2385 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14238/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 17a2b4c3a5855524ad4772a17ada0dc474e2fdf3 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 17a2b4c3a5855524ad4772a17ada0dc474e2fdf3 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 17a2b4c3a5855524ad4772a17ada0dc474e2fdf3 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14238/instruction.md b/tasks/ohmyzsh__ohmyzsh-14238/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..017e3a1d5782c81840e246f88c1c5267eca9bc90 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14238/instruction.md @@ -0,0 +1,63 @@ +# Issue + +**Title:** chore(deps): bump step-security/harden-runner from 2.22.2 to 2.22.3 in the gha-minor group + +## Description + +Bumps the gha-minor group with 1 update: [step-security/harden-runner](https://github.com/step-security/harden-runner). + +Updates `step-security/harden-runner` from 2.22.2 to 2.22.3 +
                  +Release notes +

                  Sourced from step-security/harden-runner's releases.

                  +
                  +

                  v2.22.3

                  +

                  What's Changed

                  +
                    +
                  • Added support for Avrea-hosted runners (enterprise tier)
                  • +
                  • Fixed unexpected blocking of allowed connections caused by GitHub’s DNS resolver and outbound proxy experiment on GitHub-hosted Linux runners
                  • +
                  • Added a feature flag to disable implicit AWS endpoint allowances on self-hosted Linux runners (enterprise tier)
                  • +
                  +

                  Full Changelog: https://github.com/step-security/harden-runner/compare/v2.22.2...v2.22.3

                  +
                  +
                  +
                  +Commits +
                    +
                  • 46b06ce Merge pull request #711 from step-security/rc-46
                  • +
                  • f82eb4b Merge pull request #710 from h0x0er/jatin/tp-avrea
                  • +
                  • 665b85a update agent-self-hosted, agent-bravo to v1.9.5 and agent to v0.18.0
                  • +
                  • 80fffe1 detect avrea runners
                  • +
                  • See full diff in compare view
                  • +
                  +
                  +
                  + +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=step-security/harden-runner&package-manager=github_actions&previous-version=2.22.2&new-version=2.22.3)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) + +Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. + +[//]: # (dependabot-automerge-start) +[//]: # (dependabot-automerge-end) + +--- + +
                  +Dependabot commands and options +
                  + +You can trigger Dependabot actions by commenting on this PR: +- `@dependabot rebase` will rebase this PR +- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it +- `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency +- `@dependabot ignore major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) +- `@dependabot ignore minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) +- `@dependabot ignore ` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) +- `@dependabot unignore ` will remove all of the ignore conditions of the specified dependency +- `@dependabot unignore ` will remove the ignore condition of the specified dependency and ignore conditions + +
                  + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `17a2b4c3a585`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14238/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14238/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..fdd8f6bd69e1819e598b311402cb7def49fb5384 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14238/solution/patch.diff @@ -0,0 +1,74 @@ +diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml +index 7a382aae..f8bbcfce 100644 +--- a/.github/workflows/dependencies.yml ++++ b/.github/workflows/dependencies.yml +@@ -16,7 +16,7 @@ jobs: + contents: write # this is needed to push commits and branches + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 ++ uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + +diff --git a/.github/workflows/installer.yml b/.github/workflows/installer.yml +index 88f10b0b..df2f73ff 100644 +--- a/.github/workflows/installer.yml ++++ b/.github/workflows/installer.yml +@@ -26,7 +26,7 @@ jobs: + - macos-latest + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 ++ uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + +@@ -47,7 +47,7 @@ jobs: + - test + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 ++ uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + +diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml +index cedfd03b..6676ea71 100644 +--- a/.github/workflows/main.yml ++++ b/.github/workflows/main.yml +@@ -24,7 +24,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 ++ uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + +diff --git a/.github/workflows/project.yml b/.github/workflows/project.yml +index 8cbf0667..e7676294 100644 +--- a/.github/workflows/project.yml ++++ b/.github/workflows/project.yml +@@ -17,7 +17,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 ++ uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + - name: Authenticate as @ohmyzsh +diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml +index e07679e3..e57fc4e5 100644 +--- a/.github/workflows/scorecard.yml ++++ b/.github/workflows/scorecard.yml +@@ -36,7 +36,7 @@ jobs: + + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 ++ uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + diff --git a/tasks/ohmyzsh__ohmyzsh-14238/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14238/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14238/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14238/task.toml b/tasks/ohmyzsh__ohmyzsh-14238/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5f6ddf37415e5bb7f2010c6527512b31d8fe9296 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14238/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14238" +description = "chore(deps): bump step-security/harden-runner from 2.22.2 to 2.22.3 in the gha-minor group" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "17a2b4c3a5855524ad4772a17ada0dc474e2fdf3" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14238" +source_access = "auto" +built_at = "2026-11-16T16:09:56.846135+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1a85bc2cce8aa161402226a26bac57fcb488d4f1e0dc1e365651e72109aa5eb4" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-02T08:23:10Z" +diff_format = "unified" +context_files = [ + ".github/workflows/dependencies.yml", + ".github/workflows/installer.yml", + ".github/workflows/main.yml", + ".github/workflows/project.yml", + ".github/workflows/scorecard.yml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 12 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.008176+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:92947e299cd171926836448c406c576da71b2c783e3876f985a4ad9980193eaf" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14238/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14238/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14238/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14238/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14238/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..017e3a1d5782c81840e246f88c1c5267eca9bc90 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14238/tests/instruction.md @@ -0,0 +1,63 @@ +# Issue + +**Title:** chore(deps): bump step-security/harden-runner from 2.22.2 to 2.22.3 in the gha-minor group + +## Description + +Bumps the gha-minor group with 1 update: [step-security/harden-runner](https://github.com/step-security/harden-runner). + +Updates `step-security/harden-runner` from 2.22.2 to 2.22.3 +
                  +Release notes +

                  Sourced from step-security/harden-runner's releases.

                  +
                  +

                  v2.22.3

                  +

                  What's Changed

                  +
                    +
                  • Added support for Avrea-hosted runners (enterprise tier)
                  • +
                  • Fixed unexpected blocking of allowed connections caused by GitHub’s DNS resolver and outbound proxy experiment on GitHub-hosted Linux runners
                  • +
                  • Added a feature flag to disable implicit AWS endpoint allowances on self-hosted Linux runners (enterprise tier)
                  • +
                  +

                  Full Changelog: https://github.com/step-security/harden-runner/compare/v2.22.2...v2.22.3

                  +
                  +
                  +
                  +Commits +
                    +
                  • 46b06ce Merge pull request #711 from step-security/rc-46
                  • +
                  • f82eb4b Merge pull request #710 from h0x0er/jatin/tp-avrea
                  • +
                  • 665b85a update agent-self-hosted, agent-bravo to v1.9.5 and agent to v0.18.0
                  • +
                  • 80fffe1 detect avrea runners
                  • +
                  • See full diff in compare view
                  • +
                  +
                  +
                  + +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=step-security/harden-runner&package-manager=github_actions&previous-version=2.22.2&new-version=2.22.3)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) + +Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. + +[//]: # (dependabot-automerge-start) +[//]: # (dependabot-automerge-end) + +--- + +
                  +Dependabot commands and options +
                  + +You can trigger Dependabot actions by commenting on this PR: +- `@dependabot rebase` will rebase this PR +- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it +- `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency +- `@dependabot ignore major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) +- `@dependabot ignore minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) +- `@dependabot ignore ` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) +- `@dependabot unignore ` will remove all of the ignore conditions of the specified dependency +- `@dependabot unignore ` will remove the ignore condition of the specified dependency and ignore conditions + +
                  + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `17a2b4c3a585`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14238/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14238/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..fdd8f6bd69e1819e598b311402cb7def49fb5384 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14238/tests/oracle.patch @@ -0,0 +1,74 @@ +diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml +index 7a382aae..f8bbcfce 100644 +--- a/.github/workflows/dependencies.yml ++++ b/.github/workflows/dependencies.yml +@@ -16,7 +16,7 @@ jobs: + contents: write # this is needed to push commits and branches + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 ++ uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + +diff --git a/.github/workflows/installer.yml b/.github/workflows/installer.yml +index 88f10b0b..df2f73ff 100644 +--- a/.github/workflows/installer.yml ++++ b/.github/workflows/installer.yml +@@ -26,7 +26,7 @@ jobs: + - macos-latest + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 ++ uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + +@@ -47,7 +47,7 @@ jobs: + - test + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 ++ uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + +diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml +index cedfd03b..6676ea71 100644 +--- a/.github/workflows/main.yml ++++ b/.github/workflows/main.yml +@@ -24,7 +24,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 ++ uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + +diff --git a/.github/workflows/project.yml b/.github/workflows/project.yml +index 8cbf0667..e7676294 100644 +--- a/.github/workflows/project.yml ++++ b/.github/workflows/project.yml +@@ -17,7 +17,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 ++ uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + - name: Authenticate as @ohmyzsh +diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml +index e07679e3..e57fc4e5 100644 +--- a/.github/workflows/scorecard.yml ++++ b/.github/workflows/scorecard.yml +@@ -36,7 +36,7 @@ jobs: + + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@dc2769abcc0fcfbadfc1df54081c1608579ef6b2 # v2.22.2 ++ uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 + with: + egress-policy: audit + diff --git a/tasks/ohmyzsh__ohmyzsh-14238/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14238/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..daf4e552103f867a2f30d8e30bbe512f4993cc99 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14238/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 17a2b4c3a5855524ad4772a17ada0dc474e2fdf3 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14238/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14238/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14238/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14241/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14241/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7b83dc9bde7163cb3a94bad1e3dce885d3765d65 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14241/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b509b1c6ed0c1ba37de12cbd37f30b2b2f61193a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b509b1c6ed0c1ba37de12cbd37f30b2b2f61193a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b509b1c6ed0c1ba37de12cbd37f30b2b2f61193a \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14241/instruction.md b/tasks/ohmyzsh__ohmyzsh-14241/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4c663d3f5eb444fbcc5daec5ff7c461c73412226 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14241/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** fix(mvn): complete with compsys instead of compctl + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- `plugins/mvn` completes with `compdef`/`_describe` instead of `compctl`, so completion goes through compsys and tools built on it (fzf-tab, and anything else that replaces the completion widget) can take over. +- The candidates are the existing `listMavenCompletions` list, unchanged; `:` is escaped because `_describe` splits descriptions on it, which keeps goals like `dependency:tree` intact. + +## Other comments: + +AI-assisted: the completion rewrite was drafted with Claude and reviewed and tested by me on zsh 5.9, including the two-word goals (`mvn dependency:tree`, `mvn clean`) and the `-D` property entries. + +`zsh -n plugins/mvn/mvn.plugin.zsh` passes, and the repo's CI syntax loop covers this file. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b509b1c6ed0c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14241/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14241/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..2a3d3a7d78558aa5a718e6ae0c05ee92769a7dfc --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14241/solution/patch.diff @@ -0,0 +1,21 @@ +diff --git a/plugins/mvn/mvn.plugin.zsh b/plugins/mvn/mvn.plugin.zsh +index 8477722b..bfb0c280 100644 +--- a/plugins/mvn/mvn.plugin.zsh ++++ b/plugins/mvn/mvn.plugin.zsh +@@ -347,6 +347,13 @@ function listMavenCompletions { + ) + } + +-compctl -K listMavenCompletions mvn mvnw +-compctl -K listMavenCompletions mvn-color +-compctl -K listMavenCompletions mvn-or-mvnw ++# Completion, via compsys so that tools built on it (fzf-tab, etc.) can take over. ++_mvn() { ++ local -a commands ++ listMavenCompletions ++ # _describe splits entries on `:`, so escape it to keep goals like `dependency:tree`. ++ commands=("${(@)reply//:/\\:}") ++ _describe -t mvn-commands 'mvn command' commands ++} ++ ++compdef _mvn mvn mvnw mvn-color mvn-or-mvnw diff --git a/tasks/ohmyzsh__ohmyzsh-14241/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14241/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14241/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14241/task.toml b/tasks/ohmyzsh__ohmyzsh-14241/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f6e7a0b4fd3d4f72c71c354c7053e977845f52d6 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14241/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14241" +description = "fix(mvn): complete with compsys instead of compctl" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "b509b1c6ed0c1ba37de12cbd37f30b2b2f61193a" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14241" +source_access = "auto" +built_at = "2026-11-16T16:09:56.837903+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:e3b70aabc6a1b7a347e324ad4a8c7494a31184fabdbb28331ff643fceb019ff1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-09T12:36:12Z" +diff_format = "unified" +context_files = [ + "plugins/mvn/mvn.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 13 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.008685+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b22d3fb5e92e9f80485bc8aff7c5c7d45ee130f3a531b85b6136ca2d16763de0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14241/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14241/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14241/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14241/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14241/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4c663d3f5eb444fbcc5daec5ff7c461c73412226 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14241/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** fix(mvn): complete with compsys instead of compctl + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- `plugins/mvn` completes with `compdef`/`_describe` instead of `compctl`, so completion goes through compsys and tools built on it (fzf-tab, and anything else that replaces the completion widget) can take over. +- The candidates are the existing `listMavenCompletions` list, unchanged; `:` is escaped because `_describe` splits descriptions on it, which keeps goals like `dependency:tree` intact. + +## Other comments: + +AI-assisted: the completion rewrite was drafted with Claude and reviewed and tested by me on zsh 5.9, including the two-word goals (`mvn dependency:tree`, `mvn clean`) and the `-D` property entries. + +`zsh -n plugins/mvn/mvn.plugin.zsh` passes, and the repo's CI syntax loop covers this file. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b509b1c6ed0c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14241/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14241/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..2a3d3a7d78558aa5a718e6ae0c05ee92769a7dfc --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14241/tests/oracle.patch @@ -0,0 +1,21 @@ +diff --git a/plugins/mvn/mvn.plugin.zsh b/plugins/mvn/mvn.plugin.zsh +index 8477722b..bfb0c280 100644 +--- a/plugins/mvn/mvn.plugin.zsh ++++ b/plugins/mvn/mvn.plugin.zsh +@@ -347,6 +347,13 @@ function listMavenCompletions { + ) + } + +-compctl -K listMavenCompletions mvn mvnw +-compctl -K listMavenCompletions mvn-color +-compctl -K listMavenCompletions mvn-or-mvnw ++# Completion, via compsys so that tools built on it (fzf-tab, etc.) can take over. ++_mvn() { ++ local -a commands ++ listMavenCompletions ++ # _describe splits entries on `:`, so escape it to keep goals like `dependency:tree`. ++ commands=("${(@)reply//:/\\:}") ++ _describe -t mvn-commands 'mvn command' commands ++} ++ ++compdef _mvn mvn mvnw mvn-color mvn-or-mvnw diff --git a/tasks/ohmyzsh__ohmyzsh-14241/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14241/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..cf2d88566930aef4c06a047212f80d1d34e038ee --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14241/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b509b1c6ed0c1ba37de12cbd37f30b2b2f61193a > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14241/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14241/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14241/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14244/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14244/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7b83dc9bde7163cb3a94bad1e3dce885d3765d65 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14244/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b509b1c6ed0c1ba37de12cbd37f30b2b2f61193a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b509b1c6ed0c1ba37de12cbd37f30b2b2f61193a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b509b1c6ed0c1ba37de12cbd37f30b2b2f61193a \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14244/instruction.md b/tasks/ohmyzsh__ohmyzsh-14244/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e2bcbe3e4766b50565dc8b6e60aed9136dcc7761 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14244/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** fix(web-search)!: remove ask.com, which has shut down + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. (It's three lines coming out, so I'd hope so.) +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Removes the `ask` search engine and its alias. Since Ask.com has shut down on 1 May, so `ask ` opens a 404 page now, and the plain `ask` goes to their [farewell note](https://www.ask.com/) 🪦. + +## Other comments: + +RIP Jeeves. + +image + +--- + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b509b1c6ed0c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14244/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14244/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..92d6756b94d226be48694afa7cccb4fbe2844c57 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14244/solution/patch.diff @@ -0,0 +1,32 @@ +diff --git a/plugins/web-search/README.md b/plugins/web-search/README.md +index 1aaf2e5b..67a74229 100644 +--- a/plugins/web-search/README.md ++++ b/plugins/web-search/README.md +@@ -43,7 +43,6 @@ Available search contexts are: + | `wolframalpha` | `https://wolframalpha.com/input?i=` | + | `archive` | `https://web.archive.org/web/*/` | + | `scholar` | `https://scholar.google.com/scholar?q=` | +-| `ask` | `https://www.ask.com/web?q=` | + | `youtube` | `https://www.youtube.com/results?search_query=` | + | `deepl` | `https://www.deepl.com/translator#auto/auto/` | + | `dockerhub` | `https://hub.docker.com/search?q=` | +diff --git a/plugins/web-search/web-search.plugin.zsh b/plugins/web-search/web-search.plugin.zsh +index ca507b0e..9f0b913b 100644 +--- a/plugins/web-search/web-search.plugin.zsh ++++ b/plugins/web-search/web-search.plugin.zsh +@@ -24,7 +24,6 @@ function web_search() { + wolframalpha "https://www.wolframalpha.com/input/?i=" + archive "https://web.archive.org/web/*/" + scholar "https://scholar.google.com/scholar?q=" +- ask "https://www.ask.com/web?q=" + youtube "https://www.youtube.com/results?search_query=" + deepl "https://www.deepl.com/translator#auto/auto/" + dockerhub "https://hub.docker.com/search?q=" +@@ -89,7 +88,6 @@ alias stackoverflow='web_search stackoverflow' + alias wolframalpha='web_search wolframalpha' + alias archive='web_search archive' + alias scholar='web_search scholar' +-alias ask='web_search ask' + alias youtube='web_search youtube' + alias deepl='web_search deepl' + alias dockerhub='web_search dockerhub' diff --git a/tasks/ohmyzsh__ohmyzsh-14244/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14244/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14244/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14244/task.toml b/tasks/ohmyzsh__ohmyzsh-14244/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cd6bbefb50dae2e7b1b4bead8393709093597d6c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14244/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14244" +description = "fix(web-search)!: remove ask.com, which has shut down" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "b509b1c6ed0c1ba37de12cbd37f30b2b2f61193a" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14244" +source_access = "auto" +built_at = "2026-11-16T16:09:56.842273+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:cb21cacd4b2eafe1aae61b8f608fe857747c29c8d6b4ead72065dfde7c1524b0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T13:42:14Z" +diff_format = "unified" +context_files = [ + "plugins/web-search/README.md", + "plugins/web-search/web-search.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 3 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.009154+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b22d3fb5e92e9f80485bc8aff7c5c7d45ee130f3a531b85b6136ca2d16763de0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14244/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14244/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14244/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14244/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14244/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e2bcbe3e4766b50565dc8b6e60aed9136dcc7761 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14244/tests/instruction.md @@ -0,0 +1,33 @@ +# Issue + +**Title:** fix(web-search)!: remove ask.com, which has shut down + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. (It's three lines coming out, so I'd hope so.) +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- Removes the `ask` search engine and its alias. Since Ask.com has shut down on 1 May, so `ask ` opens a 404 page now, and the plain `ask` goes to their [farewell note](https://www.ask.com/) 🪦. + +## Other comments: + +RIP Jeeves. + +image + +--- + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b509b1c6ed0c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14244/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14244/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..92d6756b94d226be48694afa7cccb4fbe2844c57 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14244/tests/oracle.patch @@ -0,0 +1,32 @@ +diff --git a/plugins/web-search/README.md b/plugins/web-search/README.md +index 1aaf2e5b..67a74229 100644 +--- a/plugins/web-search/README.md ++++ b/plugins/web-search/README.md +@@ -43,7 +43,6 @@ Available search contexts are: + | `wolframalpha` | `https://wolframalpha.com/input?i=` | + | `archive` | `https://web.archive.org/web/*/` | + | `scholar` | `https://scholar.google.com/scholar?q=` | +-| `ask` | `https://www.ask.com/web?q=` | + | `youtube` | `https://www.youtube.com/results?search_query=` | + | `deepl` | `https://www.deepl.com/translator#auto/auto/` | + | `dockerhub` | `https://hub.docker.com/search?q=` | +diff --git a/plugins/web-search/web-search.plugin.zsh b/plugins/web-search/web-search.plugin.zsh +index ca507b0e..9f0b913b 100644 +--- a/plugins/web-search/web-search.plugin.zsh ++++ b/plugins/web-search/web-search.plugin.zsh +@@ -24,7 +24,6 @@ function web_search() { + wolframalpha "https://www.wolframalpha.com/input/?i=" + archive "https://web.archive.org/web/*/" + scholar "https://scholar.google.com/scholar?q=" +- ask "https://www.ask.com/web?q=" + youtube "https://www.youtube.com/results?search_query=" + deepl "https://www.deepl.com/translator#auto/auto/" + dockerhub "https://hub.docker.com/search?q=" +@@ -89,7 +88,6 @@ alias stackoverflow='web_search stackoverflow' + alias wolframalpha='web_search wolframalpha' + alias archive='web_search archive' + alias scholar='web_search scholar' +-alias ask='web_search ask' + alias youtube='web_search youtube' + alias deepl='web_search deepl' + alias dockerhub='web_search dockerhub' diff --git a/tasks/ohmyzsh__ohmyzsh-14244/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14244/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..cf2d88566930aef4c06a047212f80d1d34e038ee --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14244/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b509b1c6ed0c1ba37de12cbd37f30b2b2f61193a > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14244/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14244/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14244/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14246/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14246/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7b83dc9bde7163cb3a94bad1e3dce885d3765d65 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14246/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin b509b1c6ed0c1ba37de12cbd37f30b2b2f61193a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard b509b1c6ed0c1ba37de12cbd37f30b2b2f61193a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base b509b1c6ed0c1ba37de12cbd37f30b2b2f61193a \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14246/instruction.md b/tasks/ohmyzsh__ohmyzsh-14246/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5167e0c8bb520fbd58a7a3c5dde9f3f0aeecc367 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14246/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** fix(timer): round duration before splitting off minutes + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- timer plugin: `__timer_format_duration` split off the minutes before rounding the seconds, so a duration just under a minute boundary was displayed as `60.0s`, and longer ones as e.g. `1m60.0s`. The duration is now rounded to the displayed precision first (as an integer count of precision units) and only then split into minutes and seconds, so `59.97` displays as `1m0.0s` and `119.97` as `2m0.0s`. +- Added `plugins/timer/tests/timer.test.zsh` covering the boundary cases at precision 0, 1 and 2. + +## Other comments: + +AI disclosure: this change was prepared with AI assistance (Claude Code). I reviewed the diff and ran the tests myself. + +Testing: `zsh -df plugins/timer/tests/timer.test.zsh` — with the old implementation 6 of the 14 cases fail (the `60.0s` / `1m60.0s` ones), with this change all 14 pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b509b1c6ed0c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14246/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14246/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..beae501267e08e2acf691fef3b9f1b4c8f799652 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14246/solution/patch.diff @@ -0,0 +1,66 @@ +diff --git a/plugins/timer/tests/timer.test.zsh b/plugins/timer/tests/timer.test.zsh +new file mode 100644 +index 00000000..d0184ac9 +--- /dev/null ++++ b/plugins/timer/tests/timer.test.zsh +@@ -0,0 +1,39 @@ ++#!/usr/bin/env zsh ++ ++# Run with: zsh -df plugins/timer/tests/timer.test.zsh ++emulate -L zsh ++ ++source "${0:A:h:h}/timer.plugin.zsh" ++ ++typeset -i failures=0 tests=0 ++ ++check_duration() { ++ local precision=$1 duration=$2 expected=$3 ++ local output=$(TIMER_PRECISION=$precision __timer_format_duration $duration) ++ (( tests++ )) ++ ++ if [[ $output == "$expected" ]]; then ++ print -r -- "PASS: $duration with precision $precision -> $output" ++ else ++ print -u2 -r -- "FAIL: $duration with precision $precision -> $output (expected $expected)" ++ (( failures++ )) ++ fi ++} ++ ++check_duration 1 0.04 /0.0s ++check_duration 1 3.04 /3.0s ++check_duration 1 40.0 /40.0s ++check_duration 1 59.94 /59.9s ++check_duration 1 59.97 /1m0.0s ++check_duration 1 61.5 /1m1.5s ++check_duration 1 73.0 /1m13.0s ++check_duration 1 119.97 /2m0.0s ++check_duration 1 3599.99 /60m0.0s ++check_duration 2 59.996 /1m0.00s ++check_duration 2 0.02 /0.02s ++check_duration 0 1.4 /1s ++check_duration 0 59.6 /1m0s ++check_duration 0 119.5 /2m0s ++ ++print -r -- "$tests tests, $failures failures" ++(( failures == 0 )) +diff --git a/plugins/timer/timer.plugin.zsh b/plugins/timer/timer.plugin.zsh +index 6baf1f68..22f17052 100644 +--- a/plugins/timer/timer.plugin.zsh ++++ b/plugins/timer/timer.plugin.zsh +@@ -6,8 +6,14 @@ __timer_current_time() { + } + + __timer_format_duration() { +- local mins=$(printf '%.0f' $(($(IFS='.' read int dec <<< "$1"; echo $int) / 60))) +- local secs=$(printf "%.${TIMER_PRECISION:-1}f" $(($1 - 60 * mins))) ++ local -i precision=${TIMER_PRECISION:-1} ++ local -i scale=$(( 10 ** precision )) ++ # Round to the displayed precision before splitting off the minutes, ++ # so that e.g. 59.97s is shown as 1m0.0s instead of 60.0s ++ local -i units ++ (( units = $1 * scale + 0.5 )) ++ local -i mins=$(( units / (60 * scale) )) ++ local secs=$(printf "%.${precision}f" $(( (units - 60 * scale * mins) / (scale * 1.0) ))) + local duration_str=$(echo "${mins}m${secs}s") + local format="${TIMER_FORMAT:-/%d}" + echo "${format//\%d/${duration_str#0m}}" diff --git a/tasks/ohmyzsh__ohmyzsh-14246/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14246/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14246/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14246/task.toml b/tasks/ohmyzsh__ohmyzsh-14246/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8c2f8a294f897d51b4468e9f4523d4ad9990bd48 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14246/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14246" +description = "fix(timer): round duration before splitting off minutes" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "b509b1c6ed0c1ba37de12cbd37f30b2b2f61193a" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14246" +source_access = "auto" +built_at = "2026-11-16T16:09:56.844078+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3b007cebd8433dfad52213663840c7016e45f74640de6b690d02a8bb94c4810b" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-06T13:40:49Z" +diff_format = "unified" +context_files = [ + "plugins/timer/tests/timer.test.zsh", + "plugins/timer/timer.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 49 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.009666+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:b22d3fb5e92e9f80485bc8aff7c5c7d45ee130f3a531b85b6136ca2d16763de0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14246/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14246/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14246/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14246/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14246/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5167e0c8bb520fbd58a7a3c5dde9f3f0aeecc367 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14246/tests/instruction.md @@ -0,0 +1,32 @@ +# Issue + +**Title:** fix(timer): round duration before splitting off minutes + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. + +## Changes: + +- timer plugin: `__timer_format_duration` split off the minutes before rounding the seconds, so a duration just under a minute boundary was displayed as `60.0s`, and longer ones as e.g. `1m60.0s`. The duration is now rounded to the displayed precision first (as an integer count of precision units) and only then split into minutes and seconds, so `59.97` displays as `1m0.0s` and `119.97` as `2m0.0s`. +- Added `plugins/timer/tests/timer.test.zsh` covering the boundary cases at precision 0, 1 and 2. + +## Other comments: + +AI disclosure: this change was prepared with AI assistance (Claude Code). I reviewed the diff and ran the tests myself. + +Testing: `zsh -df plugins/timer/tests/timer.test.zsh` — with the old implementation 6 of the 14 cases fail (the `60.0s` / `1m60.0s` ones), with this change all 14 pass. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `b509b1c6ed0c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14246/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14246/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..beae501267e08e2acf691fef3b9f1b4c8f799652 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14246/tests/oracle.patch @@ -0,0 +1,66 @@ +diff --git a/plugins/timer/tests/timer.test.zsh b/plugins/timer/tests/timer.test.zsh +new file mode 100644 +index 00000000..d0184ac9 +--- /dev/null ++++ b/plugins/timer/tests/timer.test.zsh +@@ -0,0 +1,39 @@ ++#!/usr/bin/env zsh ++ ++# Run with: zsh -df plugins/timer/tests/timer.test.zsh ++emulate -L zsh ++ ++source "${0:A:h:h}/timer.plugin.zsh" ++ ++typeset -i failures=0 tests=0 ++ ++check_duration() { ++ local precision=$1 duration=$2 expected=$3 ++ local output=$(TIMER_PRECISION=$precision __timer_format_duration $duration) ++ (( tests++ )) ++ ++ if [[ $output == "$expected" ]]; then ++ print -r -- "PASS: $duration with precision $precision -> $output" ++ else ++ print -u2 -r -- "FAIL: $duration with precision $precision -> $output (expected $expected)" ++ (( failures++ )) ++ fi ++} ++ ++check_duration 1 0.04 /0.0s ++check_duration 1 3.04 /3.0s ++check_duration 1 40.0 /40.0s ++check_duration 1 59.94 /59.9s ++check_duration 1 59.97 /1m0.0s ++check_duration 1 61.5 /1m1.5s ++check_duration 1 73.0 /1m13.0s ++check_duration 1 119.97 /2m0.0s ++check_duration 1 3599.99 /60m0.0s ++check_duration 2 59.996 /1m0.00s ++check_duration 2 0.02 /0.02s ++check_duration 0 1.4 /1s ++check_duration 0 59.6 /1m0s ++check_duration 0 119.5 /2m0s ++ ++print -r -- "$tests tests, $failures failures" ++(( failures == 0 )) +diff --git a/plugins/timer/timer.plugin.zsh b/plugins/timer/timer.plugin.zsh +index 6baf1f68..22f17052 100644 +--- a/plugins/timer/timer.plugin.zsh ++++ b/plugins/timer/timer.plugin.zsh +@@ -6,8 +6,14 @@ __timer_current_time() { + } + + __timer_format_duration() { +- local mins=$(printf '%.0f' $(($(IFS='.' read int dec <<< "$1"; echo $int) / 60))) +- local secs=$(printf "%.${TIMER_PRECISION:-1}f" $(($1 - 60 * mins))) ++ local -i precision=${TIMER_PRECISION:-1} ++ local -i scale=$(( 10 ** precision )) ++ # Round to the displayed precision before splitting off the minutes, ++ # so that e.g. 59.97s is shown as 1m0.0s instead of 60.0s ++ local -i units ++ (( units = $1 * scale + 0.5 )) ++ local -i mins=$(( units / (60 * scale) )) ++ local secs=$(printf "%.${precision}f" $(( (units - 60 * scale * mins) / (scale * 1.0) ))) + local duration_str=$(echo "${mins}m${secs}s") + local format="${TIMER_FORMAT:-/%d}" + echo "${format//\%d/${duration_str#0m}}" diff --git a/tasks/ohmyzsh__ohmyzsh-14246/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14246/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..cf2d88566930aef4c06a047212f80d1d34e038ee --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14246/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace b509b1c6ed0c1ba37de12cbd37f30b2b2f61193a > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14246/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14246/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14246/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14248/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14248/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1d67a4b7b83a88f44fb3e85758c66fa2fdce76c9 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14248/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin cca3bdfbef8c52ef8939ce7911ff68852b949daa 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard cca3bdfbef8c52ef8939ce7911ff68852b949daa \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base cca3bdfbef8c52ef8939ce7911ff68852b949daa \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14248/instruction.md b/tasks/ohmyzsh__ohmyzsh-14248/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eeb2bad7065ec129a946e74436adca12461a57d5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14248/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** feat(core): invite users to star the repo on github + +## Description + +Adds a short line to the install and update success messages that invites users to star the repo on GitHub. The star is yellow, and the link uses the existing `fmt_link` helper. + +``` +★ Enjoying Oh My Zsh? Star us on GitHub +``` + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `cca3bdfbef8c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14248/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14248/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..28c3709b44ba4d5c686ad36dc69da0d5ed39f4f4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14248/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/tools/install.sh b/tools/install.sh +index 4a02eff5..e676a8e9 100755 +--- a/tools/install.sh ++++ b/tools/install.sh +@@ -528,6 +528,7 @@ print_success() { + "$(fmt_code "$(fmt_link ".zshrc" "file://$zdot/.zshrc" --text)")" \ + "file to select plugins, themes, and options." + printf '\n' ++ printf '%s\n' "${FMT_YELLOW}★${FMT_RESET} Enjoying Oh My Zsh? Star us on $(fmt_link GitHub https://github.com/ohmyzsh/ohmyzsh)" + printf '%s\n' "• Follow along on X ($(fmt_link @ohmyzsh https://x.com/ohmyzsh)) or Bluesky ($(fmt_link @ohmyz.sh https://bsky.app/profile/ohmyz.sh))" + printf '%s\n' "• Questions or ideas? Join the community on $(fmt_link Discord https://discord.gg/ohmyzsh)" + printf '%s\n' "• Help support the project: sponsor us on $(fmt_link "Open Collective" https://opencollective.com/ohmyzsh)," +diff --git a/tools/upgrade.sh b/tools/upgrade.sh +index 22b3ac9a..f90c1024 100755 +--- a/tools/upgrade.sh ++++ b/tools/upgrade.sh +@@ -311,6 +311,9 @@ if perform_update; then + printf '%s %s %s %s /____/ %s %s %s %s\n' $RAINBOW $RESET + printf '\n' + printf "${BLUE}%s${RESET}\n\n" "$message" ++ printf "${YELLOW}${BOLD}★${RESET} ${BLUE}${BOLD}%s %s${RESET}\n" \ ++ "Enjoying Oh My Zsh? Star us on" \ ++ "$(fmt_link GitHub https://github.com/ohmyzsh/ohmyzsh)" + printf "${BLUE}${BOLD}%s %s %s %s${RESET}\n" \ + "Follow along on X" "($(fmt_link @ohmyzsh https://x.com/ohmyzsh))" \ + "or Bluesky" "($(fmt_link @ohmyz.sh https://bsky.app/profile/ohmyz.sh))" diff --git a/tasks/ohmyzsh__ohmyzsh-14248/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14248/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14248/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14248/task.toml b/tasks/ohmyzsh__ohmyzsh-14248/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1303fde96d9d6e83be59c9e0c07888fe375a608a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14248/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14248" +description = "feat(core): invite users to star the repo on github" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "cca3bdfbef8c52ef8939ce7911ff68852b949daa" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14248" +source_access = "auto" +built_at = "2026-11-16T16:09:56.840708+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:6783768a9a10d4cf11fc34f890b6cf737cd7ea32dcccd6c4d9793166b0df29f5" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-09T12:32:35Z" +diff_format = "unified" +context_files = [ + "tools/install.sh", + "tools/upgrade.sh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.010131+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e6b4767f4b299d8468613ec8469dc1ad5a17bde4b008e124e8c3e70dfccff568" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14248/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14248/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14248/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14248/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14248/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eeb2bad7065ec129a946e74436adca12461a57d5 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14248/tests/instruction.md @@ -0,0 +1,17 @@ +# Issue + +**Title:** feat(core): invite users to star the repo on github + +## Description + +Adds a short line to the install and update success messages that invites users to star the repo on GitHub. The star is yellow, and the link uses the existing `fmt_link` helper. + +``` +★ Enjoying Oh My Zsh? Star us on GitHub +``` + +🤖 Generated with [Claude Code](https://claude.com/claude-code) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `cca3bdfbef8c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14248/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14248/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..28c3709b44ba4d5c686ad36dc69da0d5ed39f4f4 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14248/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/tools/install.sh b/tools/install.sh +index 4a02eff5..e676a8e9 100755 +--- a/tools/install.sh ++++ b/tools/install.sh +@@ -528,6 +528,7 @@ print_success() { + "$(fmt_code "$(fmt_link ".zshrc" "file://$zdot/.zshrc" --text)")" \ + "file to select plugins, themes, and options." + printf '\n' ++ printf '%s\n' "${FMT_YELLOW}★${FMT_RESET} Enjoying Oh My Zsh? Star us on $(fmt_link GitHub https://github.com/ohmyzsh/ohmyzsh)" + printf '%s\n' "• Follow along on X ($(fmt_link @ohmyzsh https://x.com/ohmyzsh)) or Bluesky ($(fmt_link @ohmyz.sh https://bsky.app/profile/ohmyz.sh))" + printf '%s\n' "• Questions or ideas? Join the community on $(fmt_link Discord https://discord.gg/ohmyzsh)" + printf '%s\n' "• Help support the project: sponsor us on $(fmt_link "Open Collective" https://opencollective.com/ohmyzsh)," +diff --git a/tools/upgrade.sh b/tools/upgrade.sh +index 22b3ac9a..f90c1024 100755 +--- a/tools/upgrade.sh ++++ b/tools/upgrade.sh +@@ -311,6 +311,9 @@ if perform_update; then + printf '%s %s %s %s /____/ %s %s %s %s\n' $RAINBOW $RESET + printf '\n' + printf "${BLUE}%s${RESET}\n\n" "$message" ++ printf "${YELLOW}${BOLD}★${RESET} ${BLUE}${BOLD}%s %s${RESET}\n" \ ++ "Enjoying Oh My Zsh? Star us on" \ ++ "$(fmt_link GitHub https://github.com/ohmyzsh/ohmyzsh)" + printf "${BLUE}${BOLD}%s %s %s %s${RESET}\n" \ + "Follow along on X" "($(fmt_link @ohmyzsh https://x.com/ohmyzsh))" \ + "or Bluesky" "($(fmt_link @ohmyz.sh https://bsky.app/profile/ohmyz.sh))" diff --git a/tasks/ohmyzsh__ohmyzsh-14248/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14248/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8ba115241258f07812e3e50c4e92e75b13ac3878 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14248/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace cca3bdfbef8c52ef8939ce7911ff68852b949daa > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14248/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14248/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14248/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14250/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14250/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1d67a4b7b83a88f44fb3e85758c66fa2fdce76c9 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14250/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin cca3bdfbef8c52ef8939ce7911ff68852b949daa 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard cca3bdfbef8c52ef8939ce7911ff68852b949daa \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base cca3bdfbef8c52ef8939ce7911ff68852b949daa \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14250/instruction.md b/tasks/ohmyzsh__ohmyzsh-14250/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af1bf48cc5a7875cdb3c09befca9ee67b25ac7ff --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14250/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** fix(npm): replace removed `npm bin` in `npmE` + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. (no new ones, just mending an old one) + +## Changes: + +- `npmE` has been broken since npm 9 , so the plugin's own example, `npmE gulp`, just gives `command not found: gulp` now. It uses `$(npm root)/.bin` instead, which is the folder `npm bin` used to print inside a project. + +## Other comments: + +Tried it on npm 12 from a subfolder of a project - master can't find the script in `node_modules/.bin`, and this runs it. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `cca3bdfbef8c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14250/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14250/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..eab289be88ac1958a267ebcd8818198593ed23f0 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14250/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/plugins/npm/README.md b/plugins/npm/README.md +index 7848a129..952d24f1 100644 +--- a/plugins/npm/README.md ++++ b/plugins/npm/README.md +@@ -16,7 +16,7 @@ plugins=(... npm) + | `npmS` | `npm i -S` | Install and save to dependencies in your package.json | + | `npmD` | `npm i -D` | Install and save to dev-dependencies in your package.json | + | `npmF` | `npm i -f` | Force install from remote registries ignoring local cache | +-| `npmE` | `PATH="$(npm bin)":"$PATH"` | Run command from node_modules folder based on current directory | ++| `npmE` | `PATH="$(npm root)/.bin":"$PATH"` | Run command from node_modules folder based on current directory | + | `npmO` | `npm outdated` | Check which npm modules are outdated | + | `npmU` | `npm update` | Update all the packages listed to the latest version | + | `npmV` | `npm -v` | Check package versions | +diff --git a/plugins/npm/npm.plugin.zsh b/plugins/npm/npm.plugin.zsh +index c333f76e..0477cddf 100644 +--- a/plugins/npm/npm.plugin.zsh ++++ b/plugins/npm/npm.plugin.zsh +@@ -32,7 +32,7 @@ alias npmF='npm i -f' + + # Execute command from node_modules folder based on current directory + # i.e npmE gulp +-alias npmE='PATH="$(npm bin)":"$PATH"' ++alias npmE='PATH="$(npm root)/.bin":"$PATH"' + + # Check which npm modules are outdated + alias npmO="npm outdated" diff --git a/tasks/ohmyzsh__ohmyzsh-14250/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14250/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14250/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14250/task.toml b/tasks/ohmyzsh__ohmyzsh-14250/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8ba7a9dbfa357b5045c289d5f4ab2a13ac7014c1 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14250/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14250" +description = "fix(npm): replace removed `npm bin` in `npmE`" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "cca3bdfbef8c52ef8939ce7911ff68852b949daa" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14250" +source_access = "auto" +built_at = "2026-11-16T16:09:56.839354+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1a4539efee9778c78b5bfab57e52ba45aec5bd8ac9d6169749e6ce06f25e7255" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-09T12:34:48Z" +diff_format = "unified" +context_files = [ + "plugins/npm/README.md", + "plugins/npm/npm.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.010629+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:e6b4767f4b299d8468613ec8469dc1ad5a17bde4b008e124e8c3e70dfccff568" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14250/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14250/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14250/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14250/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14250/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af1bf48cc5a7875cdb3c09befca9ee67b25ac7ff --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14250/tests/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** fix(npm): replace removed `npm bin` in `npmE` + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] If I used AI tools (ChatGPT, Claude, Gemini, etc.) to assist with this contribution, I've disclosed it below. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. +- [ ] If the code introduces new aliases, I provide a valid use case for all plugin users down below. (no new ones, just mending an old one) + +## Changes: + +- `npmE` has been broken since npm 9 , so the plugin's own example, `npmE gulp`, just gives `command not found: gulp` now. It uses `$(npm root)/.bin` instead, which is the folder `npm bin` used to print inside a project. + +## Other comments: + +Tried it on npm 12 from a subfolder of a project - master can't find the script in `node_modules/.bin`, and this runs it. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `cca3bdfbef8c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14250/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14250/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..eab289be88ac1958a267ebcd8818198593ed23f0 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14250/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/plugins/npm/README.md b/plugins/npm/README.md +index 7848a129..952d24f1 100644 +--- a/plugins/npm/README.md ++++ b/plugins/npm/README.md +@@ -16,7 +16,7 @@ plugins=(... npm) + | `npmS` | `npm i -S` | Install and save to dependencies in your package.json | + | `npmD` | `npm i -D` | Install and save to dev-dependencies in your package.json | + | `npmF` | `npm i -f` | Force install from remote registries ignoring local cache | +-| `npmE` | `PATH="$(npm bin)":"$PATH"` | Run command from node_modules folder based on current directory | ++| `npmE` | `PATH="$(npm root)/.bin":"$PATH"` | Run command from node_modules folder based on current directory | + | `npmO` | `npm outdated` | Check which npm modules are outdated | + | `npmU` | `npm update` | Update all the packages listed to the latest version | + | `npmV` | `npm -v` | Check package versions | +diff --git a/plugins/npm/npm.plugin.zsh b/plugins/npm/npm.plugin.zsh +index c333f76e..0477cddf 100644 +--- a/plugins/npm/npm.plugin.zsh ++++ b/plugins/npm/npm.plugin.zsh +@@ -32,7 +32,7 @@ alias npmF='npm i -f' + + # Execute command from node_modules folder based on current directory + # i.e npmE gulp +-alias npmE='PATH="$(npm bin)":"$PATH"' ++alias npmE='PATH="$(npm root)/.bin":"$PATH"' + + # Check which npm modules are outdated + alias npmO="npm outdated" diff --git a/tasks/ohmyzsh__ohmyzsh-14250/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14250/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8ba115241258f07812e3e50c4e92e75b13ac3878 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14250/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace cca3bdfbef8c52ef8939ce7911ff68852b949daa > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14250/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14250/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14250/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-14254/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-14254/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..076866eb1a347738be159867d661aec31dae0d78 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14254/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6010fb6260f359e71d99ba25f05f9215809b3ed2 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6010fb6260f359e71d99ba25f05f9215809b3ed2 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6010fb6260f359e71d99ba25f05f9215809b3ed2 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-14254/instruction.md b/tasks/ohmyzsh__ohmyzsh-14254/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6c7b1e09478f5b8791f133e4a0f516b8f51cce0e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14254/instruction.md @@ -0,0 +1,67 @@ +# Issue + +**Title:** chore(deps): bump step-security/harden-runner from 2.22.3 to 2.22.4 in the gha-minor group + +## Description + +Bumps the gha-minor group with 1 update: [step-security/harden-runner](https://github.com/step-security/harden-runner). + +Updates `step-security/harden-runner` from 2.22.3 to 2.22.4 +
                  +Release notes +

                  Sourced from step-security/harden-runner's releases.

                  +
                  +

                  v2.22.4

                  +

                  What's Changed

                  +
                    +
                  • Fixed a Linux agent memory leak that could cause runners to run out of memory during jobs with heavy process or network activity.
                  • +
                  • The workaround for GitHub’s DNS resolver and outbound proxy experiment on GitHub-hosted Linux runners now defaults to enabled when feature flags can’t be fetched.
                  • +
                  • Improved HTTP/2 TLS interception on Linux (enterprise tier).
                  • +
                  • Added retries for failed monitoring API requests, improving reliability of monitoring initialization and raw-event uploads.
                  • +
                  +

                  Full Changelog: https://github.com/step-security/harden-runner/compare/v2.22.3...v2.22.4

                  +
                  +
                  +
                  +Commits +
                    +
                  • 1d88384 Merge pull request #716 from step-security/rc-48
                  • +
                  • 26249c0 Merge pull request #712 from Prateek-stepsecurity/pn/monitor-retry
                  • +
                  • b5a70cf Treat 409 from /monitor as terminal and add retry tests
                  • +
                  • 0a48cce Retry /monitor call up to 3 times on failure
                  • +
                  • 967c33e Merge pull request #715 from step-security/rc-47
                  • +
                  • 4fa77e8 Merge pull request #714 from h0x0er/jatin/agent-v1.9.6-v0.18.1
                  • +
                  • dd2b975 bump agent versions
                  • +
                  • See full diff in compare view
                  • +
                  +
                  +
                  + +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=step-security/harden-runner&package-manager=github_actions&previous-version=2.22.3&new-version=2.22.4)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) + +Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. + +[//]: # (dependabot-automerge-start) +[//]: # (dependabot-automerge-end) + +--- + +
                  +Dependabot commands and options +
                  + +You can trigger Dependabot actions by commenting on this PR: +- `@dependabot rebase` will rebase this PR +- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it +- `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency +- `@dependabot ignore major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) +- `@dependabot ignore minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) +- `@dependabot ignore ` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) +- `@dependabot unignore ` will remove all of the ignore conditions of the specified dependency +- `@dependabot unignore ` will remove the ignore condition of the specified dependency and ignore conditions + +
                  + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6010fb6260f3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14254/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-14254/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..f0ba487296c633066946bad82dfbf9f6a0be7504 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14254/solution/patch.diff @@ -0,0 +1,74 @@ +diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml +index f8bbcfce..dafe1852 100644 +--- a/.github/workflows/dependencies.yml ++++ b/.github/workflows/dependencies.yml +@@ -16,7 +16,7 @@ jobs: + contents: write # this is needed to push commits and branches + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 ++ uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + +diff --git a/.github/workflows/installer.yml b/.github/workflows/installer.yml +index df2f73ff..5d1a82d1 100644 +--- a/.github/workflows/installer.yml ++++ b/.github/workflows/installer.yml +@@ -26,7 +26,7 @@ jobs: + - macos-latest + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 ++ uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + +@@ -47,7 +47,7 @@ jobs: + - test + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 ++ uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + +diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml +index 6676ea71..102420af 100644 +--- a/.github/workflows/main.yml ++++ b/.github/workflows/main.yml +@@ -24,7 +24,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 ++ uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + +diff --git a/.github/workflows/project.yml b/.github/workflows/project.yml +index e7676294..c958f9d9 100644 +--- a/.github/workflows/project.yml ++++ b/.github/workflows/project.yml +@@ -17,7 +17,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 ++ uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - name: Authenticate as @ohmyzsh +diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml +index abfb76bd..4968fa9e 100644 +--- a/.github/workflows/scorecard.yml ++++ b/.github/workflows/scorecard.yml +@@ -36,7 +36,7 @@ jobs: + + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 ++ uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + diff --git a/tasks/ohmyzsh__ohmyzsh-14254/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-14254/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14254/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-14254/task.toml b/tasks/ohmyzsh__ohmyzsh-14254/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..27d6b7535cdf0ba8f4b4f84a7481ea669e0df492 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14254/task.toml @@ -0,0 +1,72 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-14254" +description = "chore(deps): bump step-security/harden-runner from 2.22.3 to 2.22.4 in the gha-minor group" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "6010fb6260f359e71d99ba25f05f9215809b3ed2" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/14254" +source_access = "auto" +built_at = "2026-11-16T16:09:56.835900+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:3348f04be5ba1d7daed33c6be10c42564963577bcb0ddf5835906da1c0dda2f1" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-11-16T11:59:30Z" +diff_format = "unified" +context_files = [ + ".github/workflows/dependencies.yml", + ".github/workflows/installer.yml", + ".github/workflows/main.yml", + ".github/workflows/project.yml", + ".github/workflows/scorecard.yml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 12 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.011167+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2dc955988b5098683e12af7a092dd410b877c7272e47615e458849d13ddc62f2" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-14254/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-14254/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14254/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-14254/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-14254/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6c7b1e09478f5b8791f133e4a0f516b8f51cce0e --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14254/tests/instruction.md @@ -0,0 +1,67 @@ +# Issue + +**Title:** chore(deps): bump step-security/harden-runner from 2.22.3 to 2.22.4 in the gha-minor group + +## Description + +Bumps the gha-minor group with 1 update: [step-security/harden-runner](https://github.com/step-security/harden-runner). + +Updates `step-security/harden-runner` from 2.22.3 to 2.22.4 +
                  +Release notes +

                  Sourced from step-security/harden-runner's releases.

                  +
                  +

                  v2.22.4

                  +

                  What's Changed

                  +
                    +
                  • Fixed a Linux agent memory leak that could cause runners to run out of memory during jobs with heavy process or network activity.
                  • +
                  • The workaround for GitHub’s DNS resolver and outbound proxy experiment on GitHub-hosted Linux runners now defaults to enabled when feature flags can’t be fetched.
                  • +
                  • Improved HTTP/2 TLS interception on Linux (enterprise tier).
                  • +
                  • Added retries for failed monitoring API requests, improving reliability of monitoring initialization and raw-event uploads.
                  • +
                  +

                  Full Changelog: https://github.com/step-security/harden-runner/compare/v2.22.3...v2.22.4

                  +
                  +
                  +
                  +Commits +
                    +
                  • 1d88384 Merge pull request #716 from step-security/rc-48
                  • +
                  • 26249c0 Merge pull request #712 from Prateek-stepsecurity/pn/monitor-retry
                  • +
                  • b5a70cf Treat 409 from /monitor as terminal and add retry tests
                  • +
                  • 0a48cce Retry /monitor call up to 3 times on failure
                  • +
                  • 967c33e Merge pull request #715 from step-security/rc-47
                  • +
                  • 4fa77e8 Merge pull request #714 from h0x0er/jatin/agent-v1.9.6-v0.18.1
                  • +
                  • dd2b975 bump agent versions
                  • +
                  • See full diff in compare view
                  • +
                  +
                  +
                  + +[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=step-security/harden-runner&package-manager=github_actions&previous-version=2.22.3&new-version=2.22.4)](https://docs.github.com/en/github/managing-security-vulnerabilities/about-dependabot-security-updates#about-compatibility-scores) + +Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `@dependabot rebase`. + +[//]: # (dependabot-automerge-start) +[//]: # (dependabot-automerge-end) + +--- + +
                  +Dependabot commands and options +
                  + +You can trigger Dependabot actions by commenting on this PR: +- `@dependabot rebase` will rebase this PR +- `@dependabot recreate` will recreate this PR, overwriting any edits that have been made to it +- `@dependabot show ignore conditions` will show all of the ignore conditions of the specified dependency +- `@dependabot ignore major version` will close this group update PR and stop Dependabot creating any more for the specific dependency's major version (unless you unignore this specific dependency's major version or upgrade to it yourself) +- `@dependabot ignore minor version` will close this group update PR and stop Dependabot creating any more for the specific dependency's minor version (unless you unignore this specific dependency's minor version or upgrade to it yourself) +- `@dependabot ignore ` will close this group update PR and stop Dependabot creating any more for the specific dependency (unless you unignore this specific dependency or upgrade to it yourself) +- `@dependabot unignore ` will remove all of the ignore conditions of the specified dependency +- `@dependabot unignore ` will remove the ignore condition of the specified dependency and ignore conditions + +
                  + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6010fb6260f3`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-14254/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-14254/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..f0ba487296c633066946bad82dfbf9f6a0be7504 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14254/tests/oracle.patch @@ -0,0 +1,74 @@ +diff --git a/.github/workflows/dependencies.yml b/.github/workflows/dependencies.yml +index f8bbcfce..dafe1852 100644 +--- a/.github/workflows/dependencies.yml ++++ b/.github/workflows/dependencies.yml +@@ -16,7 +16,7 @@ jobs: + contents: write # this is needed to push commits and branches + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 ++ uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + +diff --git a/.github/workflows/installer.yml b/.github/workflows/installer.yml +index df2f73ff..5d1a82d1 100644 +--- a/.github/workflows/installer.yml ++++ b/.github/workflows/installer.yml +@@ -26,7 +26,7 @@ jobs: + - macos-latest + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 ++ uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + +@@ -47,7 +47,7 @@ jobs: + - test + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 ++ uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + +diff --git a/.github/workflows/main.yml b/.github/workflows/main.yml +index 6676ea71..102420af 100644 +--- a/.github/workflows/main.yml ++++ b/.github/workflows/main.yml +@@ -24,7 +24,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 ++ uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + +diff --git a/.github/workflows/project.yml b/.github/workflows/project.yml +index e7676294..c958f9d9 100644 +--- a/.github/workflows/project.yml ++++ b/.github/workflows/project.yml +@@ -17,7 +17,7 @@ jobs: + if: github.repository == 'ohmyzsh/ohmyzsh' + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 ++ uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + - name: Authenticate as @ohmyzsh +diff --git a/.github/workflows/scorecard.yml b/.github/workflows/scorecard.yml +index abfb76bd..4968fa9e 100644 +--- a/.github/workflows/scorecard.yml ++++ b/.github/workflows/scorecard.yml +@@ -36,7 +36,7 @@ jobs: + + steps: + - name: Harden the runner (Audit all outbound calls) +- uses: step-security/harden-runner@46b06cea07f9e64621fdf066ba77ac6915163d43 # v2.22.3 ++ uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: audit + diff --git a/tasks/ohmyzsh__ohmyzsh-14254/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-14254/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..7577ada95e92bfd0cd6081c7ad54b2ec2f96463f --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14254/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 6010fb6260f359e71d99ba25f05f9215809b3ed2 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-14254/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-14254/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-14254/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-6524/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-6524/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..65c3c26f71049e638711aa100f993fd2e373f8a7 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-6524/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 532a784b806375370022605d8be17c1116553572 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 532a784b806375370022605d8be17c1116553572 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 532a784b806375370022605d8be17c1116553572 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-6524/instruction.md b/tasks/ohmyzsh__ohmyzsh-6524/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..122edec21cc256e0c67d2b69ba42561586adddd7 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-6524/instruction.md @@ -0,0 +1,12 @@ +# Issue + +**Title:** fix(screen): respect `DISABLE_AUTO_TITLE` + +## Description + +I would like to be able to set title (permanent) for one my tab but can't do this, there is a variable in CORE of OMZ which disable auto titling, I would like same behavior to be adopted by the screen.plugin: +https://github.com/robbyrussell/oh-my-zsh/blob/master/lib/termsupport.zsh#L55 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `532a784b8063`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-6524/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-6524/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..675ddb8ab7b34b35ccad9c12041024d6b8bb7635 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-6524/solution/patch.diff @@ -0,0 +1,20 @@ +diff --git a/plugins/screen/screen.plugin.zsh b/plugins/screen/screen.plugin.zsh +index 7009e7a9..4699cfa2 100644 +--- a/plugins/screen/screen.plugin.zsh ++++ b/plugins/screen/screen.plugin.zsh +@@ -30,6 +30,8 @@ if [[ "$TERM" == screen* ]]; then + # tell GNU screen what the tab window title ($1) and the hardstatus($2) should be + function screen_set() + { ++ [[ "${DISABLE_AUTO_TITLE:-}" != true ]] || return 0 ++ + # set the tab window title (%t) for screen + print -nR $'\033k'$1$'\033'\\\ + +@@ -51,4 +53,4 @@ if [[ "$TERM" == screen* ]]; then + eval "tab_hardstatus=$TAB_HARDSTATUS_PREFIX:$TAB_HARDSTATUS_PROMPT" + screen_set $tab_title $tab_hardstatus + } +-fi +\ No newline at end of file ++fi diff --git a/tasks/ohmyzsh__ohmyzsh-6524/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-6524/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-6524/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-6524/task.toml b/tasks/ohmyzsh__ohmyzsh-6524/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5a7e4c393fb8a3f19e59b94de6d7bf6f62131bbd --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-6524/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-6524" +description = "fix(screen): respect `DISABLE_AUTO_TITLE`" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "532a784b806375370022605d8be17c1116553572" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/6524" +source_access = "auto" +built_at = "2026-11-16T16:09:56.957132+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:574fa21a3f7b47bf8ebd4c11de66e8b35f66b6fcd2442235feb1369787cc3306" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-14T19:32:25Z" +diff_format = "unified" +context_files = [ + "plugins/screen/screen.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.011732+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:1f311b9529ccc77695cb53aa96c54f9c9d4e9f9afe5b35208421cbfd3217d12d" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-6524/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-6524/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-6524/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-6524/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-6524/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..122edec21cc256e0c67d2b69ba42561586adddd7 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-6524/tests/instruction.md @@ -0,0 +1,12 @@ +# Issue + +**Title:** fix(screen): respect `DISABLE_AUTO_TITLE` + +## Description + +I would like to be able to set title (permanent) for one my tab but can't do this, there is a variable in CORE of OMZ which disable auto titling, I would like same behavior to be adopted by the screen.plugin: +https://github.com/robbyrussell/oh-my-zsh/blob/master/lib/termsupport.zsh#L55 + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `532a784b8063`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-6524/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-6524/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..675ddb8ab7b34b35ccad9c12041024d6b8bb7635 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-6524/tests/oracle.patch @@ -0,0 +1,20 @@ +diff --git a/plugins/screen/screen.plugin.zsh b/plugins/screen/screen.plugin.zsh +index 7009e7a9..4699cfa2 100644 +--- a/plugins/screen/screen.plugin.zsh ++++ b/plugins/screen/screen.plugin.zsh +@@ -30,6 +30,8 @@ if [[ "$TERM" == screen* ]]; then + # tell GNU screen what the tab window title ($1) and the hardstatus($2) should be + function screen_set() + { ++ [[ "${DISABLE_AUTO_TITLE:-}" != true ]] || return 0 ++ + # set the tab window title (%t) for screen + print -nR $'\033k'$1$'\033'\\\ + +@@ -51,4 +53,4 @@ if [[ "$TERM" == screen* ]]; then + eval "tab_hardstatus=$TAB_HARDSTATUS_PREFIX:$TAB_HARDSTATUS_PROMPT" + screen_set $tab_title $tab_hardstatus + } +-fi +\ No newline at end of file ++fi diff --git a/tasks/ohmyzsh__ohmyzsh-6524/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-6524/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ada13ff383987eb45a546d8b1ce8b7717e522e79 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-6524/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 532a784b806375370022605d8be17c1116553572 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-6524/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-6524/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-6524/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-8924/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-8924/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8ea784efe7854780469e2bb00823dd1aa6f32008 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-8924/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin bf77e350e04bd202921a50529e4f54deba3db7e2 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard bf77e350e04bd202921a50529e4f54deba3db7e2 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base bf77e350e04bd202921a50529e4f54deba3db7e2 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-8924/instruction.md b/tasks/ohmyzsh__ohmyzsh-8924/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..784ff115774ae7c278bff1288a6650735b96c601 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-8924/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Create go_prompt_info to add go version to prompts + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. + +## Changes: + +- [...] + +## Other comments: + +... + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bf77e350e04b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-8924/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-8924/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..66bcc94c6c2c5f516ead68198b4ed7813ee4a028 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-8924/solution/patch.diff @@ -0,0 +1,52 @@ +diff --git a/lib/prompt_info_functions.zsh b/lib/prompt_info_functions.zsh +index 722ae58c..9b8e2de9 100644 +--- a/lib/prompt_info_functions.zsh ++++ b/lib/prompt_info_functions.zsh +@@ -21,6 +21,7 @@ function chruby_prompt_info \ + azure_prompt_info \ + tf_prompt_info \ + conda_prompt_info \ ++ go_prompt_info \ + { + return 1 + } +diff --git a/plugins/golang/README.md b/plugins/golang/README.md +index 80f8cf3b..610952d6 100644 +--- a/plugins/golang/README.md ++++ b/plugins/golang/README.md +@@ -39,3 +39,18 @@ plugins=(... golang) + | gov | `go vet` | Vet examines Go source code and reports suspicious constructs | + | gove | `go version` | Prints Go version | + | gow | `go work` | Work provides access to operations on workspaces | ++ ++## Prompt ++ ++This plugin provides the `go_prompt_info` function to add the installed Go ++version to your prompt. ++ ++For example: ++``` ++PROMPT="%~$ " ++RPROMPT='$(go_prompt_info)' ++``` ++changes your prompt to: ++``` ++~/go/project$ ▋ 1.22.3 ++``` +diff --git a/plugins/golang/golang.plugin.zsh b/plugins/golang/golang.plugin.zsh +index dc4d9184..48908b5d 100644 +--- a/plugins/golang/golang.plugin.zsh ++++ b/plugins/golang/golang.plugin.zsh +@@ -36,3 +36,12 @@ alias gotofx='go tool fix' + alias gov='go vet' + alias gove='go version' + alias gow='go work' ++ ++## prompt ++function go_prompt_info() { ++ (( $+commands[go] )) || return ++ local go_prompt ++ go_prompt=$(go version | awk '{ print substr($3, 3) }') ++ [[ -z "${go_prompt}" ]] && return ++ echo "${ZSH_THEME_GO_PROMPT_PREFIX}${go_prompt:gs/%/%%}${ZSH_THEME_GO_PROMPT_SUFFIX}" ++} diff --git a/tasks/ohmyzsh__ohmyzsh-8924/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-8924/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-8924/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-8924/task.toml b/tasks/ohmyzsh__ohmyzsh-8924/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c6949e92f1b766796d8354e3201d669e9ed66852 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-8924/task.toml @@ -0,0 +1,70 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-8924" +description = "Create go_prompt_info to add go version to prompts" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "bf77e350e04bd202921a50529e4f54deba3db7e2" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/8924" +source_access = "auto" +built_at = "2026-11-16T16:09:56.983583+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:432fec8408d97a00f1ec07f61de18d13fc97693caefb431d2c1f08f50935b89e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-07T14:49:07Z" +diff_format = "unified" +context_files = [ + "lib/prompt_info_functions.zsh", + "plugins/golang/README.md", + "plugins/golang/golang.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 25 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.012271+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:5db987b6f9b2c41d0ea5c41f7447acabd7dcee284e131de89d7d9e4153b38a30" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-8924/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-8924/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-8924/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-8924/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-8924/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..784ff115774ae7c278bff1288a6650735b96c601 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-8924/tests/instruction.md @@ -0,0 +1,27 @@ +# Issue + +**Title:** Create go_prompt_info to add go version to prompts + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. + +## Changes: + +- [...] + +## Other comments: + +... + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `bf77e350e04b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-8924/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-8924/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..66bcc94c6c2c5f516ead68198b4ed7813ee4a028 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-8924/tests/oracle.patch @@ -0,0 +1,52 @@ +diff --git a/lib/prompt_info_functions.zsh b/lib/prompt_info_functions.zsh +index 722ae58c..9b8e2de9 100644 +--- a/lib/prompt_info_functions.zsh ++++ b/lib/prompt_info_functions.zsh +@@ -21,6 +21,7 @@ function chruby_prompt_info \ + azure_prompt_info \ + tf_prompt_info \ + conda_prompt_info \ ++ go_prompt_info \ + { + return 1 + } +diff --git a/plugins/golang/README.md b/plugins/golang/README.md +index 80f8cf3b..610952d6 100644 +--- a/plugins/golang/README.md ++++ b/plugins/golang/README.md +@@ -39,3 +39,18 @@ plugins=(... golang) + | gov | `go vet` | Vet examines Go source code and reports suspicious constructs | + | gove | `go version` | Prints Go version | + | gow | `go work` | Work provides access to operations on workspaces | ++ ++## Prompt ++ ++This plugin provides the `go_prompt_info` function to add the installed Go ++version to your prompt. ++ ++For example: ++``` ++PROMPT="%~$ " ++RPROMPT='$(go_prompt_info)' ++``` ++changes your prompt to: ++``` ++~/go/project$ ▋ 1.22.3 ++``` +diff --git a/plugins/golang/golang.plugin.zsh b/plugins/golang/golang.plugin.zsh +index dc4d9184..48908b5d 100644 +--- a/plugins/golang/golang.plugin.zsh ++++ b/plugins/golang/golang.plugin.zsh +@@ -36,3 +36,12 @@ alias gotofx='go tool fix' + alias gov='go vet' + alias gove='go version' + alias gow='go work' ++ ++## prompt ++function go_prompt_info() { ++ (( $+commands[go] )) || return ++ local go_prompt ++ go_prompt=$(go version | awk '{ print substr($3, 3) }') ++ [[ -z "${go_prompt}" ]] && return ++ echo "${ZSH_THEME_GO_PROMPT_PREFIX}${go_prompt:gs/%/%%}${ZSH_THEME_GO_PROMPT_SUFFIX}" ++} diff --git a/tasks/ohmyzsh__ohmyzsh-8924/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-8924/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5fbf313e79f0ae174c27044b653be288a38806e3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-8924/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace bf77e350e04bd202921a50529e4f54deba3db7e2 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-8924/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-8924/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-8924/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-9676/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-9676/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cc92fc8353224318839312c01cf5dd241dc598d3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9676/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 74965c96098134b192f00084f966b4b02438a739 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 74965c96098134b192f00084f966b4b02438a739 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 74965c96098134b192f00084f966b4b02438a739 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-9676/instruction.md b/tasks/ohmyzsh__ohmyzsh-9676/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c0c3b98a1f0f1be87895553c6d0ee10fd131a227 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9676/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Add git aliases + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. + +## Changes: + +I added two commands from a [git plugin for Fish shell](https://github.com/jhillyerd/plugin-git) himself based on OMZ. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `74965c960981`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-9676/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-9676/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..c751306dc7d1ae3710018b4a642ac1664d981007 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9676/solution/patch.diff @@ -0,0 +1,58 @@ +diff --git a/plugins/git/README.md b/plugins/git/README.md +index 930a4b8f..c07e1ba7 100644 +--- a/plugins/git/README.md ++++ b/plugins/git/README.md +@@ -108,6 +108,7 @@ plugins=(... git) + | `glo` | `git log --oneline --decorate` | + | `glog` | `git log --oneline --decorate --graph` | + | `gloga` | `git log --oneline --decorate --graph --all` | ++| `glom` | `git log --oneline --decorate --color $(git_main_branch)..` | + | `glp` | `git log --pretty=` | + | `glg` | `git log --stat` | + | `glgp` | `git log --stat --patch` | +@@ -155,6 +156,8 @@ plugins=(... git) + | `grba` | `git rebase --abort` | + | `grbc` | `git rebase --continue` | + | `grbi` | `git rebase --interactive` | ++| `grbmi` | `git rebase $(git_main_branch) --interactive` | ++| `grbmia` | `git rebase $(git_main_branch) --interactive --autosquash` | + | `grbo` | `git rebase --onto` | + | `grbs` | `git rebase --skip` | + | `grbd` | `git rebase $(git_develop_branch)` | +@@ -204,6 +207,7 @@ plugins=(... git) + | `gsb` | `git status --short -b` | + | `gsi` | `git submodule init` | + | `gsu` | `git submodule update` | ++| `gsuri` | `git submodule update --recursive --init` | + | `gsd` | `git svn dcommit` | + | `git-svn-dcommit-push` | `git svn dcommit && git push github $(git_main_branch):svntrunk` | + | `gsr` | `git svn rebase` | +diff --git a/plugins/git/git.plugin.zsh b/plugins/git/git.plugin.zsh +index dc0f2763..4db17b82 100644 +--- a/plugins/git/git.plugin.zsh ++++ b/plugins/git/git.plugin.zsh +@@ -253,6 +253,7 @@ alias glolm='git log $(git_main_branch) --graph --pretty="%Cred%h%Creset -%C(aut + alias glo='git log --oneline --decorate' + alias glog='git log --oneline --decorate --graph' + alias gloga='git log --oneline --decorate --graph --all' ++alias glom='git log --oneline --decorate --color $(git_main_branch)..' + + # Pretty log messages + function _git_log_prettily(){ +@@ -362,6 +363,8 @@ alias grbd='git rebase $(git_develop_branch)' + alias grbm='git rebase $(git_main_branch)' + alias grbom='git rebase origin/$(git_main_branch)' + alias grbum='git rebase upstream/$(git_main_branch)' ++alias grbmi='git rebase $(git_main_branch) --interactive' ++alias grbmia='git rebase $(git_main_branch) --interactive --autosquash' + alias grf='git reflog' + alias gr='git remote' + alias grv='git remote --verbose' +@@ -406,6 +409,7 @@ alias gss='git status --short' + alias gsb='git status --short --branch' + alias gsi='git submodule init' + alias gsu='git submodule update' ++alias gsuri='git submodule update --recursive --init' + alias gsd='git svn dcommit' + alias git-svn-dcommit-push='git svn dcommit && git push github $(git_main_branch):svntrunk' + alias gsr='git svn rebase' diff --git a/tasks/ohmyzsh__ohmyzsh-9676/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-9676/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9676/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-9676/task.toml b/tasks/ohmyzsh__ohmyzsh-9676/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dd2fa5ec21ec1f98f2352fda872f4144d6f9b09d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9676/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-9676" +description = "Add git aliases" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "74965c96098134b192f00084f966b4b02438a739" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/9676" +source_access = "auto" +built_at = "2026-11-16T16:09:56.904710+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:d4e492521dc9f9c9cc2fd13a51bd272565ad6e1609636b603b74e848885c2e33" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-28T11:22:49Z" +diff_format = "unified" +context_files = [ + "plugins/git/README.md", + "plugins/git/git.plugin.zsh", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 8 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.012798+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:6df2a89571567469831ffaa8b2615a575449c25845dfeb4197f338842424e79c" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-9676/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-9676/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9676/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-9676/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-9676/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c0c3b98a1f0f1be87895553c6d0ee10fd131a227 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9676/tests/instruction.md @@ -0,0 +1,23 @@ +# Issue + +**Title:** Add git aliases + +## Description + +## Standards checklist: + +- [x] The PR title is descriptive. +- [x] The PR doesn't replicate another PR which is already open. +- [x] I have read the contribution guide and followed all the instructions. +- [x] The code follows the code style guide detailed in the wiki. +- [x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x] The code is stable and I have tested it myself, to the best of my abilities. + +## Changes: + +I added two commands from a [git plugin for Fish shell](https://github.com/jhillyerd/plugin-git) himself based on OMZ. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `74965c960981`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-9676/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-9676/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..c751306dc7d1ae3710018b4a642ac1664d981007 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9676/tests/oracle.patch @@ -0,0 +1,58 @@ +diff --git a/plugins/git/README.md b/plugins/git/README.md +index 930a4b8f..c07e1ba7 100644 +--- a/plugins/git/README.md ++++ b/plugins/git/README.md +@@ -108,6 +108,7 @@ plugins=(... git) + | `glo` | `git log --oneline --decorate` | + | `glog` | `git log --oneline --decorate --graph` | + | `gloga` | `git log --oneline --decorate --graph --all` | ++| `glom` | `git log --oneline --decorate --color $(git_main_branch)..` | + | `glp` | `git log --pretty=` | + | `glg` | `git log --stat` | + | `glgp` | `git log --stat --patch` | +@@ -155,6 +156,8 @@ plugins=(... git) + | `grba` | `git rebase --abort` | + | `grbc` | `git rebase --continue` | + | `grbi` | `git rebase --interactive` | ++| `grbmi` | `git rebase $(git_main_branch) --interactive` | ++| `grbmia` | `git rebase $(git_main_branch) --interactive --autosquash` | + | `grbo` | `git rebase --onto` | + | `grbs` | `git rebase --skip` | + | `grbd` | `git rebase $(git_develop_branch)` | +@@ -204,6 +207,7 @@ plugins=(... git) + | `gsb` | `git status --short -b` | + | `gsi` | `git submodule init` | + | `gsu` | `git submodule update` | ++| `gsuri` | `git submodule update --recursive --init` | + | `gsd` | `git svn dcommit` | + | `git-svn-dcommit-push` | `git svn dcommit && git push github $(git_main_branch):svntrunk` | + | `gsr` | `git svn rebase` | +diff --git a/plugins/git/git.plugin.zsh b/plugins/git/git.plugin.zsh +index dc0f2763..4db17b82 100644 +--- a/plugins/git/git.plugin.zsh ++++ b/plugins/git/git.plugin.zsh +@@ -253,6 +253,7 @@ alias glolm='git log $(git_main_branch) --graph --pretty="%Cred%h%Creset -%C(aut + alias glo='git log --oneline --decorate' + alias glog='git log --oneline --decorate --graph' + alias gloga='git log --oneline --decorate --graph --all' ++alias glom='git log --oneline --decorate --color $(git_main_branch)..' + + # Pretty log messages + function _git_log_prettily(){ +@@ -362,6 +363,8 @@ alias grbd='git rebase $(git_develop_branch)' + alias grbm='git rebase $(git_main_branch)' + alias grbom='git rebase origin/$(git_main_branch)' + alias grbum='git rebase upstream/$(git_main_branch)' ++alias grbmi='git rebase $(git_main_branch) --interactive' ++alias grbmia='git rebase $(git_main_branch) --interactive --autosquash' + alias grf='git reflog' + alias gr='git remote' + alias grv='git remote --verbose' +@@ -406,6 +409,7 @@ alias gss='git status --short' + alias gsb='git status --short --branch' + alias gsi='git submodule init' + alias gsu='git submodule update' ++alias gsuri='git submodule update --recursive --init' + alias gsd='git svn dcommit' + alias git-svn-dcommit-push='git svn dcommit && git push github $(git_main_branch):svntrunk' + alias gsr='git svn rebase' diff --git a/tasks/ohmyzsh__ohmyzsh-9676/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-9676/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..bed0ef5221ecbfe151f2f011933aca5c19853403 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9676/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 74965c96098134b192f00084f966b4b02438a739 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-9676/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-9676/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9676/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/ohmyzsh__ohmyzsh-9723/environment/Dockerfile b/tasks/ohmyzsh__ohmyzsh-9723/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d4f9997e152e0e2b27b35a02e1713bd25d5b0c94 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9723/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/ohmyzsh/ohmyzsh.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/ohmyzsh/ohmyzsh.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/ohmyzsh/ohmyzsh.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 0ab87c26c17171ae6162ff379a0c704fa57dff2e 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 0ab87c26c17171ae6162ff379a0c704fa57dff2e \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 0ab87c26c17171ae6162ff379a0c704fa57dff2e \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/ohmyzsh__ohmyzsh-9723/instruction.md b/tasks/ohmyzsh__ohmyzsh-9723/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..172c0214ee7790262ecd985d0e0913f7afe741e3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9723/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** Make the root shell distinguishable by changing the $PS1 color and prompt for it in strug.zsh-theme + +## Description + +## Standards checklist: + + + +- [ x] The PR title is descriptive. +- [ x] The PR doesn't replicate another PR which is already open. +- [ x] I have read the contribution guide and followed all the instructions. +- [ x] The code follows the code style guide detailed in the wiki. +- [ x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x ] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x ] The code is stable and I have tested it myself, to the best of my abilities. + +## Changes: + +- Turned $PS1 color from green to red in root shell +- Changed root prompt from Dollar to Hashtag in root shell + +## Other comments: +@ncanceill + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0ab87c26c171`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-9723/solution/patch.diff b/tasks/ohmyzsh__ohmyzsh-9723/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..48f84d7750752c1aa2ae3640b28593a37d36721c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9723/solution/patch.diff @@ -0,0 +1,15 @@ +diff --git a/themes/strug.zsh-theme b/themes/strug.zsh-theme +index 89b56b00..74f69e27 100644 +--- a/themes/strug.zsh-theme ++++ b/themes/strug.zsh-theme +@@ -4,8 +4,8 @@ export LSCOLORS=dxFxCxDxBxegedabagacad + + local git_branch='$(git_prompt_info)%{$reset_color%}$(git_remote_status)' + +-PROMPT="%{$fg[green]%}╭─%n@%m %{$reset_color%}%{$fg[yellow]%}in %~ %{$reset_color%}${git_branch} +-%{$fg[green]%}╰\$ %{$reset_color%}" ++PROMPT="%{%(#~$fg[red]~$fg[green])%}╭─%n@%m %{$reset_color%}%{$fg[yellow]%}in %~ %{$reset_color%}${git_branch} ++%{%(#~$fg[red]~$fg[green])%}╰%(#~#~\$) %{$reset_color%}" + + ZSH_THEME_GIT_PROMPT_PREFIX="%{$fg_bold[yellow]%}on " + ZSH_THEME_GIT_PROMPT_SUFFIX="%{$reset_color%}" diff --git a/tasks/ohmyzsh__ohmyzsh-9723/solution/solve.sh b/tasks/ohmyzsh__ohmyzsh-9723/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9723/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/ohmyzsh__ohmyzsh-9723/task.toml b/tasks/ohmyzsh__ohmyzsh-9723/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4d548feb7a432820841bd8bd870bf812b0a03a4b --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9723/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/ohmyzsh__ohmyzsh-9723" +description = "Make the root shell distinguishable by changing the $PS1 color and prompt for it in strug.zsh-theme" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "ohmyzsh", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "ohmyzsh/ohmyzsh" +ref = "0ab87c26c17171ae6162ff379a0c704fa57dff2e" +reference = "https://github.com/ohmyzsh/ohmyzsh/pull/9723" +source_access = "auto" +built_at = "2026-11-16T16:09:56.863219+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:30c754ed76cb9bf324026608a1a9fb1dec29b608cc381665827aeb538a103204" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2026-09-08T21:36:56Z" +diff_format = "unified" +context_files = [ + "themes/strug.zsh-theme", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.013289+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:024cd8975c6fc074cd7c922686bc32f1c0411e8872b22da7dc4bf2282f0fb71e" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/ohmyzsh__ohmyzsh-9723/tests/capture.py b/tasks/ohmyzsh__ohmyzsh-9723/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9723/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ohmyzsh__ohmyzsh-9723/tests/instruction.md b/tasks/ohmyzsh__ohmyzsh-9723/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..172c0214ee7790262ecd985d0e0913f7afe741e3 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9723/tests/instruction.md @@ -0,0 +1,29 @@ +# Issue + +**Title:** Make the root shell distinguishable by changing the $PS1 color and prompt for it in strug.zsh-theme + +## Description + +## Standards checklist: + + + +- [ x] The PR title is descriptive. +- [ x] The PR doesn't replicate another PR which is already open. +- [ x] I have read the contribution guide and followed all the instructions. +- [ x] The code follows the code style guide detailed in the wiki. +- [ x] The code is mine or it's from somewhere with an MIT-compatible license. +- [x ] The code is efficient, to the best of my ability, and does not waste computer resources. +- [x ] The code is stable and I have tested it myself, to the best of my abilities. + +## Changes: + +- Turned $PS1 color from green to red in root shell +- Changed root prompt from Dollar to Hashtag in root shell + +## Other comments: +@ncanceill + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `0ab87c26c171`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/ohmyzsh__ohmyzsh-9723/tests/oracle.patch b/tasks/ohmyzsh__ohmyzsh-9723/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..48f84d7750752c1aa2ae3640b28593a37d36721c --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9723/tests/oracle.patch @@ -0,0 +1,15 @@ +diff --git a/themes/strug.zsh-theme b/themes/strug.zsh-theme +index 89b56b00..74f69e27 100644 +--- a/themes/strug.zsh-theme ++++ b/themes/strug.zsh-theme +@@ -4,8 +4,8 @@ export LSCOLORS=dxFxCxDxBxegedabagacad + + local git_branch='$(git_prompt_info)%{$reset_color%}$(git_remote_status)' + +-PROMPT="%{$fg[green]%}╭─%n@%m %{$reset_color%}%{$fg[yellow]%}in %~ %{$reset_color%}${git_branch} +-%{$fg[green]%}╰\$ %{$reset_color%}" ++PROMPT="%{%(#~$fg[red]~$fg[green])%}╭─%n@%m %{$reset_color%}%{$fg[yellow]%}in %~ %{$reset_color%}${git_branch} ++%{%(#~$fg[red]~$fg[green])%}╰%(#~#~\$) %{$reset_color%}" + + ZSH_THEME_GIT_PROMPT_PREFIX="%{$fg_bold[yellow]%}on " + ZSH_THEME_GIT_PROMPT_SUFFIX="%{$reset_color%}" diff --git a/tasks/ohmyzsh__ohmyzsh-9723/tests/test.sh b/tasks/ohmyzsh__ohmyzsh-9723/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..b2af4c251ca36c082b9d8ec45ef6aa183db998d8 --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9723/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 0ab87c26c17171ae6162ff379a0c704fa57dff2e > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/ohmyzsh__ohmyzsh-9723/tests/verifier.py b/tasks/ohmyzsh__ohmyzsh-9723/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/ohmyzsh__ohmyzsh-9723/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/open-telemetry__opentelemetry-proto-595/environment/Dockerfile b/tasks/open-telemetry__opentelemetry-proto-595/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e0d8a0d4b6978fa5da3502a0890117c9cacacf6c --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-595/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/open-telemetry/opentelemetry-proto.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 804814948d9fe5c54d3dc1bb32e5cf4d0b8917e7 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 804814948d9fe5c54d3dc1bb32e5cf4d0b8917e7 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 804814948d9fe5c54d3dc1bb32e5cf4d0b8917e7 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/open-telemetry__opentelemetry-proto-595/instruction.md b/tasks/open-telemetry__opentelemetry-proto-595/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ebe2a9b2fe32c8b27ad515c13ab02e659c5d50d0 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-595/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Profiles: Remove has_* debug info fields, they are moving to attributes. + +## Description + +The has_* debug info fields were derived from the pprof format. We decided to move them to attributes, see + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `804814948d9f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-595/solution/patch.diff b/tasks/open-telemetry__opentelemetry-proto-595/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9e8ab7b2ea2f917e405f6a772de2af3ef7dd40f4 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-595/solution/patch.diff @@ -0,0 +1,16 @@ +diff --git a/opentelemetry/proto/profiles/v1development/profiles.proto b/opentelemetry/proto/profiles/v1development/profiles.proto +index 0bb1dc2..91301b6 100644 +--- a/opentelemetry/proto/profiles/v1development/profiles.proto ++++ b/opentelemetry/proto/profiles/v1development/profiles.proto +@@ -439,11 +439,6 @@ message Mapping { + int32 filename_strindex = 4; // Index into ProfilesDictionary.string_table. + // References to attributes in ProfilesDictionary.attribute_table. [optional] + repeated int32 attribute_indices = 5; +- // The following fields indicate the resolution of symbolic info. +- bool has_functions = 6; +- bool has_filenames = 7; +- bool has_line_numbers = 8; +- bool has_inline_frames = 9; + } + + // Describes function and line table debug information. diff --git a/tasks/open-telemetry__opentelemetry-proto-595/solution/solve.sh b/tasks/open-telemetry__opentelemetry-proto-595/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-595/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/open-telemetry__opentelemetry-proto-595/task.toml b/tasks/open-telemetry__opentelemetry-proto-595/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5189483c0b682406ffa72a333b6b2d99bd76c3bd --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-595/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/open-telemetry__opentelemetry-proto-595" +description = "Profiles: Remove has_* debug info fields, they are moving to attributes." + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "opentelemetry-proto", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "open-telemetry/opentelemetry-proto" +ref = "804814948d9fe5c54d3dc1bb32e5cf4d0b8917e7" +reference = "https://github.com/open-telemetry/opentelemetry-proto/pull/595" +source_access = "auto" +built_at = "2026-11-16T16:09:42.160471+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:356d173d44aa7196cc96e794d161d88d0125314cce064a8ba3a402b8ec17c00e" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-08-07T14:46:29Z" +diff_format = "unified" +context_files = [ + "opentelemetry/proto/profiles/v1development/profiles.proto", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.013753+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2e29710938f1538d2412debed991000d246252877f9cb4d36d959dffa75fd515" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/open-telemetry__opentelemetry-proto-595/tests/capture.py b/tasks/open-telemetry__opentelemetry-proto-595/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-595/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/open-telemetry__opentelemetry-proto-595/tests/instruction.md b/tasks/open-telemetry__opentelemetry-proto-595/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ebe2a9b2fe32c8b27ad515c13ab02e659c5d50d0 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-595/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Profiles: Remove has_* debug info fields, they are moving to attributes. + +## Description + +The has_* debug info fields were derived from the pprof format. We decided to move them to attributes, see + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `804814948d9f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-595/tests/oracle.patch b/tasks/open-telemetry__opentelemetry-proto-595/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9e8ab7b2ea2f917e405f6a772de2af3ef7dd40f4 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-595/tests/oracle.patch @@ -0,0 +1,16 @@ +diff --git a/opentelemetry/proto/profiles/v1development/profiles.proto b/opentelemetry/proto/profiles/v1development/profiles.proto +index 0bb1dc2..91301b6 100644 +--- a/opentelemetry/proto/profiles/v1development/profiles.proto ++++ b/opentelemetry/proto/profiles/v1development/profiles.proto +@@ -439,11 +439,6 @@ message Mapping { + int32 filename_strindex = 4; // Index into ProfilesDictionary.string_table. + // References to attributes in ProfilesDictionary.attribute_table. [optional] + repeated int32 attribute_indices = 5; +- // The following fields indicate the resolution of symbolic info. +- bool has_functions = 6; +- bool has_filenames = 7; +- bool has_line_numbers = 8; +- bool has_inline_frames = 9; + } + + // Describes function and line table debug information. diff --git a/tasks/open-telemetry__opentelemetry-proto-595/tests/test.sh b/tasks/open-telemetry__opentelemetry-proto-595/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..8bf56a447bc13e0d692eb34ec635dfa3ce534aab --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-595/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 804814948d9fe5c54d3dc1bb32e5cf4d0b8917e7 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/open-telemetry__opentelemetry-proto-595/tests/verifier.py b/tasks/open-telemetry__opentelemetry-proto-595/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-595/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/open-telemetry__opentelemetry-proto-619/environment/Dockerfile b/tasks/open-telemetry__opentelemetry-proto-619/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..40e4a129f6aa41659b12c741a0b99fd88eecaf21 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-619/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/open-telemetry/opentelemetry-proto.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 298a60fa953bbdcfa8be54a9dccb6f90cb0711d9 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 298a60fa953bbdcfa8be54a9dccb6f90cb0711d9 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 298a60fa953bbdcfa8be54a9dccb6f90cb0711d9 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/open-telemetry__opentelemetry-proto-619/instruction.md b/tasks/open-telemetry__opentelemetry-proto-619/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..73319ab9c13ec3a4e4422c5212311f0a0e1224e6 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-619/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** Clarify when bucket_counts array may be empty + +## Description + +The current definition says: + +"The number of elements in bucket_counts array must be by one + greater than the number of elements in explicit_bounds array." + +However, it also says "bucket_counts is an optional field", which +means its length can be 0, which then in turn means the length of +explicit_bounds must be -1, which is impossible. + +We clarify that it is a valid situation to have both bucket_counts and explicit_bounds arrays empty. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `298a60fa953b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-619/solution/patch.diff b/tasks/open-telemetry__opentelemetry-proto-619/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e7091470d7599d9cfc7f79d2336e1aeb7d01c40c --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-619/solution/patch.diff @@ -0,0 +1,25 @@ +diff --git a/opentelemetry/proto/metrics/v1/metrics.proto b/opentelemetry/proto/metrics/v1/metrics.proto +index 2bae75a..3fc2d35 100644 +--- a/opentelemetry/proto/metrics/v1/metrics.proto ++++ b/opentelemetry/proto/metrics/v1/metrics.proto +@@ -461,7 +461,9 @@ message HistogramDataPoint { + // The sum of the bucket_counts must equal the value in the count field. + // + // The number of elements in bucket_counts array must be by one greater than +- // the number of elements in explicit_bounds array. ++ // the number of elements in explicit_bounds array. The exception to this rule ++ // is when the length of bucket_counts is 0, then the length of explicit_bounds ++ // must also be 0. + repeated fixed64 bucket_counts = 6; + + // explicit_bounds specifies buckets with explicitly defined bounds for values. +@@ -477,6 +479,9 @@ message HistogramDataPoint { + // Histogram buckets are inclusive of their upper boundary, except the last + // bucket where the boundary is at infinity. This format is intentionally + // compatible with the OpenMetrics histogram definition. ++ // ++ // If bucket_counts length is 0 then explicit_bounds length must also be 0, ++ // otherwise the data point is invalid. + repeated double explicit_bounds = 7; + + // (Optional) List of exemplars collected from diff --git a/tasks/open-telemetry__opentelemetry-proto-619/solution/solve.sh b/tasks/open-telemetry__opentelemetry-proto-619/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-619/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/open-telemetry__opentelemetry-proto-619/task.toml b/tasks/open-telemetry__opentelemetry-proto-619/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f373ea25b18503be9a89a16d02b8cacefd04d65e --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-619/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/open-telemetry__opentelemetry-proto-619" +description = "Clarify when bucket_counts array may be empty" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "opentelemetry-proto", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "open-telemetry/opentelemetry-proto" +ref = "298a60fa953bbdcfa8be54a9dccb6f90cb0711d9" +reference = "https://github.com/open-telemetry/opentelemetry-proto/pull/619" +source_access = "auto" +built_at = "2026-11-16T16:09:42.250291+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b669f06fc902b816dcbed7ed0b07f2c2ce1146eb1efead09aa2844672afc9b29" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-02-12T19:05:31Z" +diff_format = "unified" +context_files = [ + "opentelemetry/proto/metrics/v1/metrics.proto", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 7 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.014217+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:cce74591cff5d6dd64ddf5f34d124687404190dc367c077677a0bac9e15a2306" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/open-telemetry__opentelemetry-proto-619/tests/capture.py b/tasks/open-telemetry__opentelemetry-proto-619/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-619/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/open-telemetry__opentelemetry-proto-619/tests/instruction.md b/tasks/open-telemetry__opentelemetry-proto-619/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..73319ab9c13ec3a4e4422c5212311f0a0e1224e6 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-619/tests/instruction.md @@ -0,0 +1,20 @@ +# Issue + +**Title:** Clarify when bucket_counts array may be empty + +## Description + +The current definition says: + +"The number of elements in bucket_counts array must be by one + greater than the number of elements in explicit_bounds array." + +However, it also says "bucket_counts is an optional field", which +means its length can be 0, which then in turn means the length of +explicit_bounds must be -1, which is impossible. + +We clarify that it is a valid situation to have both bucket_counts and explicit_bounds arrays empty. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `298a60fa953b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-619/tests/oracle.patch b/tasks/open-telemetry__opentelemetry-proto-619/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e7091470d7599d9cfc7f79d2336e1aeb7d01c40c --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-619/tests/oracle.patch @@ -0,0 +1,25 @@ +diff --git a/opentelemetry/proto/metrics/v1/metrics.proto b/opentelemetry/proto/metrics/v1/metrics.proto +index 2bae75a..3fc2d35 100644 +--- a/opentelemetry/proto/metrics/v1/metrics.proto ++++ b/opentelemetry/proto/metrics/v1/metrics.proto +@@ -461,7 +461,9 @@ message HistogramDataPoint { + // The sum of the bucket_counts must equal the value in the count field. + // + // The number of elements in bucket_counts array must be by one greater than +- // the number of elements in explicit_bounds array. ++ // the number of elements in explicit_bounds array. The exception to this rule ++ // is when the length of bucket_counts is 0, then the length of explicit_bounds ++ // must also be 0. + repeated fixed64 bucket_counts = 6; + + // explicit_bounds specifies buckets with explicitly defined bounds for values. +@@ -477,6 +479,9 @@ message HistogramDataPoint { + // Histogram buckets are inclusive of their upper boundary, except the last + // bucket where the boundary is at infinity. This format is intentionally + // compatible with the OpenMetrics histogram definition. ++ // ++ // If bucket_counts length is 0 then explicit_bounds length must also be 0, ++ // otherwise the data point is invalid. + repeated double explicit_bounds = 7; + + // (Optional) List of exemplars collected from diff --git a/tasks/open-telemetry__opentelemetry-proto-619/tests/test.sh b/tasks/open-telemetry__opentelemetry-proto-619/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..85ab79f677acacdbe59902d4eea4073336ddb982 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-619/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 298a60fa953bbdcfa8be54a9dccb6f90cb0711d9 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/open-telemetry__opentelemetry-proto-619/tests/verifier.py b/tasks/open-telemetry__opentelemetry-proto-619/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-619/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/open-telemetry__opentelemetry-proto-620/environment/Dockerfile b/tasks/open-telemetry__opentelemetry-proto-620/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..af0e42d2b47a9d8235e862766d5846584232a852 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-620/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/open-telemetry/opentelemetry-proto.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 6a4f4e4fd867eda646ae14604dbc773e2516826a 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 6a4f4e4fd867eda646ae14604dbc773e2516826a \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 6a4f4e4fd867eda646ae14604dbc773e2516826a \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/open-telemetry__opentelemetry-proto-620/instruction.md b/tasks/open-telemetry__opentelemetry-proto-620/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..955eb34c83646257bdb97b31ac71a8df92b5df8e --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-620/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** profiles: switch default sample type index from string_table to sample_type array + +## Description + +For visibility: @open-telemetry/profiling-maintainers + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6a4f4e4fd867`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-620/solution/patch.diff b/tasks/open-telemetry__opentelemetry-proto-620/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..e48b47d314f595e0761ef176b2c33179ba530dcd --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-620/solution/patch.diff @@ -0,0 +1,16 @@ +diff --git a/opentelemetry/proto/profiles/v1development/profiles.proto b/opentelemetry/proto/profiles/v1development/profiles.proto +index 1cb20b0..f3821d0 100644 +--- a/opentelemetry/proto/profiles/v1development/profiles.proto ++++ b/opentelemetry/proto/profiles/v1development/profiles.proto +@@ -231,9 +231,8 @@ message Profile { + // for human-friendly content. The profile must stay functional if this field + // is cleaned. + repeated int32 comment_strindices = 15; // Indices into string table. +- // Index into the string table of the type of the preferred sample +- // value. If unset, clients should default to the last sample value. +- int32 default_sample_type_strindex = 16; ++ // Index into the sample_type array to the default sample type. ++ int32 default_sample_type_index = 16; + + + // A globally unique identifier for a profile. The ID is a 16-byte array. An ID with diff --git a/tasks/open-telemetry__opentelemetry-proto-620/solution/solve.sh b/tasks/open-telemetry__opentelemetry-proto-620/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-620/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/open-telemetry__opentelemetry-proto-620/task.toml b/tasks/open-telemetry__opentelemetry-proto-620/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..339c19408053ea54ef4f4a19f245bd140bdb21fe --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-620/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/open-telemetry__opentelemetry-proto-620" +description = "profiles: switch default sample type index from string_table to sample_type array" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "opentelemetry-proto", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "open-telemetry/opentelemetry-proto" +ref = "6a4f4e4fd867eda646ae14604dbc773e2516826a" +reference = "https://github.com/open-telemetry/opentelemetry-proto/pull/620" +source_access = "auto" +built_at = "2026-11-16T16:09:42.253357+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:5c250ef17c10d367068aa490f0eeee493e25168431dda4514627efd18273a1a0" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-02-11T15:14:29Z" +diff_format = "unified" +context_files = [ + "opentelemetry/proto/profiles/v1development/profiles.proto", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 5 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.014725+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:04077e694feaee136cbab0723c479b82686b8392b8e80c2a1999c7dfc24a02ba" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/open-telemetry__opentelemetry-proto-620/tests/capture.py b/tasks/open-telemetry__opentelemetry-proto-620/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-620/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/open-telemetry__opentelemetry-proto-620/tests/instruction.md b/tasks/open-telemetry__opentelemetry-proto-620/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..955eb34c83646257bdb97b31ac71a8df92b5df8e --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-620/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** profiles: switch default sample type index from string_table to sample_type array + +## Description + +For visibility: @open-telemetry/profiling-maintainers + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `6a4f4e4fd867`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-620/tests/oracle.patch b/tasks/open-telemetry__opentelemetry-proto-620/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..e48b47d314f595e0761ef176b2c33179ba530dcd --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-620/tests/oracle.patch @@ -0,0 +1,16 @@ +diff --git a/opentelemetry/proto/profiles/v1development/profiles.proto b/opentelemetry/proto/profiles/v1development/profiles.proto +index 1cb20b0..f3821d0 100644 +--- a/opentelemetry/proto/profiles/v1development/profiles.proto ++++ b/opentelemetry/proto/profiles/v1development/profiles.proto +@@ -231,9 +231,8 @@ message Profile { + // for human-friendly content. The profile must stay functional if this field + // is cleaned. + repeated int32 comment_strindices = 15; // Indices into string table. +- // Index into the string table of the type of the preferred sample +- // value. If unset, clients should default to the last sample value. +- int32 default_sample_type_strindex = 16; ++ // Index into the sample_type array to the default sample type. ++ int32 default_sample_type_index = 16; + + + // A globally unique identifier for a profile. The ID is a 16-byte array. An ID with diff --git a/tasks/open-telemetry__opentelemetry-proto-620/tests/test.sh b/tasks/open-telemetry__opentelemetry-proto-620/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..e46196544efcc7b8a44be7d01e36b5256a19fac4 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-620/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 6a4f4e4fd867eda646ae14604dbc773e2516826a > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/open-telemetry__opentelemetry-proto-620/tests/verifier.py b/tasks/open-telemetry__opentelemetry-proto-620/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-620/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/open-telemetry__opentelemetry-proto-621/environment/Dockerfile b/tasks/open-telemetry__opentelemetry-proto-621/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..87d288f7186bfd016ff032835e37effbe0e3f42c --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-621/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/open-telemetry/opentelemetry-proto.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d7770822d70c7bd47a6891fc9faacc66fc4af3d3 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d7770822d70c7bd47a6891fc9faacc66fc4af3d3 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d7770822d70c7bd47a6891fc9faacc66fc4af3d3 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/open-telemetry__opentelemetry-proto-621/instruction.md b/tasks/open-telemetry__opentelemetry-proto-621/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dcbf3f2b3dbf502b4032b5e6621031e14464769f --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-621/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** profiles: clarify use of optional fields in message Line and message Function + +## Description + +Add clarifying comments for the use of optional fields in message Line and message Function + +For visibility: @open-telemetry/profiling-maintainers + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d7770822d70c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-621/solution/patch.diff b/tasks/open-telemetry__opentelemetry-proto-621/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..7d5e1e6f29bfe49a64a74ba5c83a7ca12beac673 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-621/solution/patch.diff @@ -0,0 +1,37 @@ +diff --git a/opentelemetry/proto/profiles/v1development/profiles.proto b/opentelemetry/proto/profiles/v1development/profiles.proto +index f3821d0..a9e6f6f 100644 +--- a/opentelemetry/proto/profiles/v1development/profiles.proto ++++ b/opentelemetry/proto/profiles/v1development/profiles.proto +@@ -453,22 +453,22 @@ message Location { + message Line { + // Reference to function in Profile.function_table. + int32 function_index = 1; +- // Line number in source code. ++ // Line number in source code. 0 means unset. + int64 line = 2; +- // Column number in source code. ++ // Column number in source code. 0 means unset. + int64 column = 3; + } + + // Describes a function, including its human-readable name, system name, + // source file, and starting line number in the source. + message Function { +- // Name of the function, in human-readable form if available. +- int32 name_strindex = 1; // Index into string table +- // Name of the function, as identified by the system. +- // For instance, it can be a C++ mangled name. +- int32 system_name_strindex = 2; // Index into string table +- // Source file containing the function. +- int32 filename_strindex = 3; // Index into string table +- // Line number in source file. ++ // Function name. Empty string if not available. ++ int32 name_strindex = 1; ++ // Function name, as identified by the system. For instance, ++ // it can be a C++ mangled name. Empty string if not available. ++ int32 system_name_strindex = 2; ++ // Source file containing the function. Empty string if not available. ++ int32 filename_strindex = 3; ++ // Line number in source file. 0 means unset. + int64 start_line = 4; + } diff --git a/tasks/open-telemetry__opentelemetry-proto-621/solution/solve.sh b/tasks/open-telemetry__opentelemetry-proto-621/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-621/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/open-telemetry__opentelemetry-proto-621/task.toml b/tasks/open-telemetry__opentelemetry-proto-621/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a5383e778b669ef3cec197bc4965d7599f38a2cc --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-621/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/open-telemetry__opentelemetry-proto-621" +description = "profiles: clarify use of optional fields in message Line and message Function" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "opentelemetry-proto", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "open-telemetry/opentelemetry-proto" +ref = "d7770822d70c7bd47a6891fc9faacc66fc4af3d3" +reference = "https://github.com/open-telemetry/opentelemetry-proto/pull/621" +source_access = "auto" +built_at = "2026-11-16T16:09:42.251909+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:dd39acf1ce097aa8844b16e8b76b48f4bf564dbea2507f007fcbfdf9a2893f42" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-03-26T21:21:15Z" +diff_format = "unified" +context_files = [ + "opentelemetry/proto/profiles/v1development/profiles.proto", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 20 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.015179+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:c524d18089985deb72bea8ac88c3c647b40b0808ef7cfd707de2c9003907aeda" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/open-telemetry__opentelemetry-proto-621/tests/capture.py b/tasks/open-telemetry__opentelemetry-proto-621/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-621/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/open-telemetry__opentelemetry-proto-621/tests/instruction.md b/tasks/open-telemetry__opentelemetry-proto-621/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dcbf3f2b3dbf502b4032b5e6621031e14464769f --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-621/tests/instruction.md @@ -0,0 +1,13 @@ +# Issue + +**Title:** profiles: clarify use of optional fields in message Line and message Function + +## Description + +Add clarifying comments for the use of optional fields in message Line and message Function + +For visibility: @open-telemetry/profiling-maintainers + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d7770822d70c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-621/tests/oracle.patch b/tasks/open-telemetry__opentelemetry-proto-621/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..7d5e1e6f29bfe49a64a74ba5c83a7ca12beac673 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-621/tests/oracle.patch @@ -0,0 +1,37 @@ +diff --git a/opentelemetry/proto/profiles/v1development/profiles.proto b/opentelemetry/proto/profiles/v1development/profiles.proto +index f3821d0..a9e6f6f 100644 +--- a/opentelemetry/proto/profiles/v1development/profiles.proto ++++ b/opentelemetry/proto/profiles/v1development/profiles.proto +@@ -453,22 +453,22 @@ message Location { + message Line { + // Reference to function in Profile.function_table. + int32 function_index = 1; +- // Line number in source code. ++ // Line number in source code. 0 means unset. + int64 line = 2; +- // Column number in source code. ++ // Column number in source code. 0 means unset. + int64 column = 3; + } + + // Describes a function, including its human-readable name, system name, + // source file, and starting line number in the source. + message Function { +- // Name of the function, in human-readable form if available. +- int32 name_strindex = 1; // Index into string table +- // Name of the function, as identified by the system. +- // For instance, it can be a C++ mangled name. +- int32 system_name_strindex = 2; // Index into string table +- // Source file containing the function. +- int32 filename_strindex = 3; // Index into string table +- // Line number in source file. ++ // Function name. Empty string if not available. ++ int32 name_strindex = 1; ++ // Function name, as identified by the system. For instance, ++ // it can be a C++ mangled name. Empty string if not available. ++ int32 system_name_strindex = 2; ++ // Source file containing the function. Empty string if not available. ++ int32 filename_strindex = 3; ++ // Line number in source file. 0 means unset. + int64 start_line = 4; + } diff --git a/tasks/open-telemetry__opentelemetry-proto-621/tests/test.sh b/tasks/open-telemetry__opentelemetry-proto-621/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..48760be89caa12deee895813d507a124e4a5546f --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-621/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d7770822d70c7bd47a6891fc9faacc66fc4af3d3 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/open-telemetry__opentelemetry-proto-621/tests/verifier.py b/tasks/open-telemetry__opentelemetry-proto-621/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-621/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/open-telemetry__opentelemetry-proto-625/environment/Dockerfile b/tasks/open-telemetry__opentelemetry-proto-625/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0ef97169ce666c57a90fe2af7efccf13912a0e34 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-625/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/open-telemetry/opentelemetry-proto.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 101755aefb5bdb6fbbf1c403763da9e14b1a45cc 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 101755aefb5bdb6fbbf1c403763da9e14b1a45cc \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 101755aefb5bdb6fbbf1c403763da9e14b1a45cc \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/open-telemetry__opentelemetry-proto-625/instruction.md b/tasks/open-telemetry__opentelemetry-proto-625/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..81d656eac6e6c21eea8bc25a3f654312bdcadf1a --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-625/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Bump checkout action, use commit tags for security reason + +## Description + +(no description provided in source PR) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `101755aefb5b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-625/solution/patch.diff b/tasks/open-telemetry__opentelemetry-proto-625/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..58d38f103aa3d989a1c57f889a2e2cdd87543afe --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-625/solution/patch.diff @@ -0,0 +1,192 @@ +diff --git a/.github/workflows/build-check.yaml b/.github/workflows/build-check.yaml +index d84a42a..9d40f96 100644 +--- a/.github/workflows/build-check.yaml ++++ b/.github/workflows/build-check.yaml +@@ -10,116 +10,139 @@ jobs: + docker-pull: + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make docker-pull ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Run docker pull ++ run: make docker-pull + + gen-cpp: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-cpp ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate C++ ++ run: make gen-cpp + + gen-csharp: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-csharp ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate C# ++ run: make gen-csharp + + gen-go: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-go ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate GoLang ++ run: make gen-go + + gen-java: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-java ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate Java ++ run: make gen-java + + gen-objc: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-objc ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate ObjC ++ run: make gen-objc + + gen-openapi: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-openapi ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate OpenAPI ++ run: make gen-openapi + + gen-php: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-php ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate PhP ++ run: make gen-php + + gen-python: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-python ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate Python ++ run: make gen-python + + gen-ruby: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-ruby ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate Ruby ++ run: make gen-ruby + + gen-kotlin: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-kotlin ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate Kotlin ++ run: make gen-kotlin + + breaking-change: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- # breaking-change checks against last published release which is determined +- # using the last published tag +- - name: Get tags +- run: git fetch --tags origin +- - name: Run make breaking-change with json output to annotate PR +- # Formats JSON output into Github workflow commands +- # https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-an-error-message +- run: > +- BUF_FLAGS="--error-format json" make -s breaking-change +- | jq -rs '.[] | "::error file=\(.path),line=\(.start_line),endLine=\(.end_line),title=Buf detected breaking change \(.type)::\(.message)"' +- ; (exit ${PIPESTATUS[0]}) ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ # breaking-change checks against last published release which is determined ++ # using the last published tag ++ - name: Get tags ++ run: git fetch --tags origin ++ - name: Run make breaking-change with json output to annotate PR ++ # Formats JSON output into Github workflow commands ++ # https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-an-error-message ++ run: > ++ BUF_FLAGS="--error-format json" make -s breaking-change ++ | jq -rs '.[] | "::error file=\(.path),line=\(.start_line),endLine=\(.end_line),title=Buf detected breaking change \(.type)::\(.message)"' ++ ; (exit ${PIPESTATUS[0]}) + + markdown-link-check: + runs-on: ubuntu-latest + steps: +- - name: check out code +- uses: actions/checkout@v2 ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + +- - name: install dependencies +- run: npm install ++ - name: install dependencies ++ run: npm install + +- - name: run markdown-link-check +- run: make markdown-link-check ++ - name: run markdown-link-check ++ run: make markdown-link-check + + markdownlint: + runs-on: ubuntu-latest + steps: +- - name: check out code +- uses: actions/checkout@v2 ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + +- - name: install dependencies +- run: npm install ++ - name: install dependencies ++ run: npm install + +- - name: run markdownlint +- run: make markdownlint +\ No newline at end of file ++ - name: run markdownlint ++ run: make markdownlint +\ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-625/solution/solve.sh b/tasks/open-telemetry__opentelemetry-proto-625/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-625/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/open-telemetry__opentelemetry-proto-625/task.toml b/tasks/open-telemetry__opentelemetry-proto-625/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..85c302abbf76da421266dc8c808ae1aa69a34aca --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-625/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/open-telemetry__opentelemetry-proto-625" +description = "Bump checkout action, use commit tags for security reason" + +[metadata] +difficulty = "large" +category = "bugfix" +keywords = [ + "opentelemetry-proto", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "open-telemetry/opentelemetry-proto" +ref = "101755aefb5bdb6fbbf1c403763da9e14b1a45cc" +reference = "https://github.com/open-telemetry/opentelemetry-proto/pull/625" +source_access = "auto" +built_at = "2026-11-16T16:09:42.248662+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1f112c085fc061e5e62803e00f4c5de06ab3d59e9ecf2f5cb936bab6ec3d0065" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-02-13T23:06:17Z" +diff_format = "unified" +context_files = [ + ".github/workflows/build-check.yaml", +] +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:02.015666+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:36a7f05c4cb1b89d36bb766065490457af79a93a867013b6ae66d0afa3853c98" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/open-telemetry__opentelemetry-proto-625/tests/capture.py b/tasks/open-telemetry__opentelemetry-proto-625/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-625/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/open-telemetry__opentelemetry-proto-625/tests/instruction.md b/tasks/open-telemetry__opentelemetry-proto-625/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..81d656eac6e6c21eea8bc25a3f654312bdcadf1a --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-625/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Bump checkout action, use commit tags for security reason + +## Description + +(no description provided in source PR) + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `101755aefb5b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-625/tests/oracle.patch b/tasks/open-telemetry__opentelemetry-proto-625/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..58d38f103aa3d989a1c57f889a2e2cdd87543afe --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-625/tests/oracle.patch @@ -0,0 +1,192 @@ +diff --git a/.github/workflows/build-check.yaml b/.github/workflows/build-check.yaml +index d84a42a..9d40f96 100644 +--- a/.github/workflows/build-check.yaml ++++ b/.github/workflows/build-check.yaml +@@ -10,116 +10,139 @@ jobs: + docker-pull: + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make docker-pull ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Run docker pull ++ run: make docker-pull + + gen-cpp: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-cpp ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate C++ ++ run: make gen-cpp + + gen-csharp: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-csharp ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate C# ++ run: make gen-csharp + + gen-go: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-go ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate GoLang ++ run: make gen-go + + gen-java: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-java ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate Java ++ run: make gen-java + + gen-objc: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-objc ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate ObjC ++ run: make gen-objc + + gen-openapi: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-openapi ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate OpenAPI ++ run: make gen-openapi + + gen-php: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-php ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate PhP ++ run: make gen-php + + gen-python: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-python ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate Python ++ run: make gen-python + + gen-ruby: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-ruby ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate Ruby ++ run: make gen-ruby + + gen-kotlin: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- - run: make gen-kotlin ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ - name: Generate Kotlin ++ run: make gen-kotlin + + breaking-change: + needs: docker-pull + runs-on: ubuntu-latest + steps: +- - uses: actions/checkout@v2 +- # breaking-change checks against last published release which is determined +- # using the last published tag +- - name: Get tags +- run: git fetch --tags origin +- - name: Run make breaking-change with json output to annotate PR +- # Formats JSON output into Github workflow commands +- # https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-an-error-message +- run: > +- BUF_FLAGS="--error-format json" make -s breaking-change +- | jq -rs '.[] | "::error file=\(.path),line=\(.start_line),endLine=\(.end_line),title=Buf detected breaking change \(.type)::\(.message)"' +- ; (exit ${PIPESTATUS[0]}) ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ # breaking-change checks against last published release which is determined ++ # using the last published tag ++ - name: Get tags ++ run: git fetch --tags origin ++ - name: Run make breaking-change with json output to annotate PR ++ # Formats JSON output into Github workflow commands ++ # https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions#setting-an-error-message ++ run: > ++ BUF_FLAGS="--error-format json" make -s breaking-change ++ | jq -rs '.[] | "::error file=\(.path),line=\(.start_line),endLine=\(.end_line),title=Buf detected breaking change \(.type)::\(.message)"' ++ ; (exit ${PIPESTATUS[0]}) + + markdown-link-check: + runs-on: ubuntu-latest + steps: +- - name: check out code +- uses: actions/checkout@v2 ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + +- - name: install dependencies +- run: npm install ++ - name: install dependencies ++ run: npm install + +- - name: run markdown-link-check +- run: make markdown-link-check ++ - name: run markdown-link-check ++ run: make markdown-link-check + + markdownlint: + runs-on: ubuntu-latest + steps: +- - name: check out code +- uses: actions/checkout@v2 ++ - name: Checkout Repo ++ uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 + +- - name: install dependencies +- run: npm install ++ - name: install dependencies ++ run: npm install + +- - name: run markdownlint +- run: make markdownlint +\ No newline at end of file ++ - name: run markdownlint ++ run: make markdownlint +\ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-625/tests/test.sh b/tasks/open-telemetry__opentelemetry-proto-625/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..78658e503f5cd9f707acedcabacffd4e1032e129 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-625/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 101755aefb5bdb6fbbf1c403763da9e14b1a45cc > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/open-telemetry__opentelemetry-proto-625/tests/verifier.py b/tasks/open-telemetry__opentelemetry-proto-625/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-625/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/open-telemetry__opentelemetry-proto-626/environment/Dockerfile b/tasks/open-telemetry__opentelemetry-proto-626/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a243ab46ee739c65c705dce5a2b4851321ce02d5 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-626/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/open-telemetry/opentelemetry-proto.git +WORKDIR /workspace +RUN git fetch --depth 1 origin d9fd878d46b1970cf72b3d11ea012fff60716aa8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard d9fd878d46b1970cf72b3d11ea012fff60716aa8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base d9fd878d46b1970cf72b3d11ea012fff60716aa8 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/open-telemetry__opentelemetry-proto-626/instruction.md b/tasks/open-telemetry__opentelemetry-proto-626/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bcccf189ae80a19aec3a996ebbce52359beea83c --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-626/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Add FOSSA scanning workflow + +## Description + +See for details + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d9fd878d46b1`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-626/solution/patch.diff b/tasks/open-telemetry__opentelemetry-proto-626/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..9f1c96dfeaad3cf9ed4331b95d6a967481208d7f --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-626/solution/patch.diff @@ -0,0 +1,26 @@ +diff --git a/.github/workflows/fossa.yml b/.github/workflows/fossa.yml +new file mode 100644 +index 0000000..3beaa09 +--- /dev/null ++++ b/.github/workflows/fossa.yml +@@ -0,0 +1,20 @@ ++name: FOSSA scanning ++ ++on: ++ push: ++ branches: ++ - main ++ ++permissions: ++ contents: read ++ ++jobs: ++ fossa: ++ runs-on: ubuntu-latest ++ steps: ++ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ ++ - uses: fossas/fossa-action@93a52ecf7c3ac7eb40f5de77fd69b1a19524de94 # v1.5.0 ++ with: ++ api-key: ${{secrets.FOSSA_API_KEY}} ++ team: OpenTelemetry diff --git a/tasks/open-telemetry__opentelemetry-proto-626/solution/solve.sh b/tasks/open-telemetry__opentelemetry-proto-626/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-626/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/open-telemetry__opentelemetry-proto-626/task.toml b/tasks/open-telemetry__opentelemetry-proto-626/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e882507036030942a0c49e231a8be2e00a0314f6 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-626/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/open-telemetry__opentelemetry-proto-626" +description = "Add FOSSA scanning workflow" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "opentelemetry-proto", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "open-telemetry/opentelemetry-proto" +ref = "d9fd878d46b1970cf72b3d11ea012fff60716aa8" +reference = "https://github.com/open-telemetry/opentelemetry-proto/pull/626" +source_access = "auto" +built_at = "2026-11-16T16:09:42.247093+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b9f115c552050dc145b1d299338796a50a52765e00a2e0d91c660707a00d4735" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-02-18T16:26:04Z" +diff_format = "unified" +context_files = [ + ".github/workflows/fossa.yml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 20 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.016120+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ca18f36072ddfb4e9b111db68a548ba4937d0754148e6b7ab22fbcb64a7acf89" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/open-telemetry__opentelemetry-proto-626/tests/capture.py b/tasks/open-telemetry__opentelemetry-proto-626/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-626/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/open-telemetry__opentelemetry-proto-626/tests/instruction.md b/tasks/open-telemetry__opentelemetry-proto-626/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bcccf189ae80a19aec3a996ebbce52359beea83c --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-626/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Add FOSSA scanning workflow + +## Description + +See for details + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `d9fd878d46b1`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-626/tests/oracle.patch b/tasks/open-telemetry__opentelemetry-proto-626/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..9f1c96dfeaad3cf9ed4331b95d6a967481208d7f --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-626/tests/oracle.patch @@ -0,0 +1,26 @@ +diff --git a/.github/workflows/fossa.yml b/.github/workflows/fossa.yml +new file mode 100644 +index 0000000..3beaa09 +--- /dev/null ++++ b/.github/workflows/fossa.yml +@@ -0,0 +1,20 @@ ++name: FOSSA scanning ++ ++on: ++ push: ++ branches: ++ - main ++ ++permissions: ++ contents: read ++ ++jobs: ++ fossa: ++ runs-on: ubuntu-latest ++ steps: ++ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ ++ - uses: fossas/fossa-action@93a52ecf7c3ac7eb40f5de77fd69b1a19524de94 # v1.5.0 ++ with: ++ api-key: ${{secrets.FOSSA_API_KEY}} ++ team: OpenTelemetry diff --git a/tasks/open-telemetry__opentelemetry-proto-626/tests/test.sh b/tasks/open-telemetry__opentelemetry-proto-626/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..0d23fa5f2abad226312096a89f0abe9049014cf3 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-626/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace d9fd878d46b1970cf72b3d11ea012fff60716aa8 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/open-telemetry__opentelemetry-proto-626/tests/verifier.py b/tasks/open-telemetry__opentelemetry-proto-626/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-626/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/open-telemetry__opentelemetry-proto-635/environment/Dockerfile b/tasks/open-telemetry__opentelemetry-proto-635/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..279a3bcea5ac664d041153c553d8c29f44c07ec5 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-635/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/open-telemetry/opentelemetry-proto.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 9d7c091a619d8f53c31cd54c0b604eec3f7611c1 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 9d7c091a619d8f53c31cd54c0b604eec3f7611c1 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 9d7c091a619d8f53c31cd54c0b604eec3f7611c1 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/open-telemetry__opentelemetry-proto-635/instruction.md b/tasks/open-telemetry__opentelemetry-proto-635/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a4b53a929166b1627b6728834dce5ff4cc7f8b60 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-635/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** Add EntityRef and use it in Resource. + +## Description + +As per [OTEP 264](https://github.com/open-telemetry/opentelemetry-specification/blob/main/oteps/entities/0264-resource-and-entities.md) - This is the proposal for representing "Entity" in OTLP. + +- Adds a new `EntityRef` message where an Entity is an object of interest in observability. + - Entity has a type (e.g. `host`, `k8s.pod`, `service`). + - Entity has a set of identifying attributes (these contribute to signal identity) + - Entity has a set of descriptive attirbutes (these are used to aide signal retreival/querying). + - Entity can be defined and versioned (e.g. semantic conventions via schema_url). +- Adds a new `entity_refs` field to `Resource` that allows distinguishing which key-value pairs in `Resource` come from which reported `Entity`. + +Please read the OTEP for details and rationale behind this protocol design. High level this meant to be: + +- Sufficient to represent entities +- Non-breaking for all OpenTelemetry users. + + +Prototypes using this protocol + +- java: +- collector: +- go: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9d7c091a619d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-635/solution/patch.diff b/tasks/open-telemetry__opentelemetry-proto-635/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..01f76b74de23c4ae6673924d3ffb9d5f047961d3 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-635/solution/patch.diff @@ -0,0 +1,59 @@ +diff --git a/opentelemetry/proto/common/v1/common.proto b/opentelemetry/proto/common/v1/common.proto +index ff8a21a..57c9f86 100644 +--- a/opentelemetry/proto/common/v1/common.proto ++++ b/opentelemetry/proto/common/v1/common.proto +@@ -79,3 +79,37 @@ message InstrumentationScope { + repeated KeyValue attributes = 3; + uint32 dropped_attributes_count = 4; + } ++ ++// A reference to an Entity. ++// Entity represents an object of interest associated with produced telemetry: e.g spans, metrics, profiles, or logs. ++// ++// Status: [Development] ++message EntityRef { ++ // The Schema URL, if known. This is the identifier of the Schema that the entity data ++ // is recorded in. To learn more about Schema URL see ++ // https://opentelemetry.io/docs/specs/otel/schemas/#schema-url ++ // ++ // This schema_url applies to the data in this message and to the Resource attributes ++ // referenced by id_keys and description_keys. ++ // TODO: discuss if we are happy with this somewhat complicated definition of what ++ // the schema_url applies to. ++ // ++ // This field obsoletes the schema_url field in ResourceMetrics/ResourceSpans/ResourceLogs. ++ string schema_url = 1; ++ ++ // Defines the type of the entity. MUST not change during the lifetime of the entity. ++ // For example: "service" or "host". This field is required and MUST not be empty ++ // for valid entities. ++ string type = 2; ++ ++ // Attribute Keys that identify the entity. ++ // MUST not change during the lifetime of the entity. The Id must contain at least one attribute. ++ // These keys MUST exist in the containing {message}.attributes. ++ repeated string id_keys = 3; ++ ++ // Descriptive (non-identifying) attribute keys of the entity. ++ // MAY change over the lifetime of the entity. MAY be empty. ++ // These attribute keys are not part of entity's identity. ++ // These keys MUST exist in the containing {message}.attributes. ++ repeated string description_keys = 4; ++} +\ No newline at end of file +diff --git a/opentelemetry/proto/resource/v1/resource.proto b/opentelemetry/proto/resource/v1/resource.proto +index 6637560..05d4456 100644 +--- a/opentelemetry/proto/resource/v1/resource.proto ++++ b/opentelemetry/proto/resource/v1/resource.proto +@@ -34,4 +34,11 @@ message Resource { + // dropped_attributes_count is the number of dropped attributes. If the value is 0, then + // no attributes were dropped. + uint32 dropped_attributes_count = 2; ++ ++ // Set of entities that participate in this Resource. ++ // ++ // Note: keys in the references MUST exist in attributes of this message. ++ // ++ // Status: [Development] ++ repeated opentelemetry.proto.common.v1.EntityRef entity_refs = 3; + } diff --git a/tasks/open-telemetry__opentelemetry-proto-635/solution/solve.sh b/tasks/open-telemetry__opentelemetry-proto-635/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-635/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/open-telemetry__opentelemetry-proto-635/task.toml b/tasks/open-telemetry__opentelemetry-proto-635/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e1cda0dbe7875ff66e28611fa3dc9a0fb83d1158 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-635/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/open-telemetry__opentelemetry-proto-635" +description = "Add EntityRef and use it in Resource." + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "opentelemetry-proto", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "open-telemetry/opentelemetry-proto" +ref = "9d7c091a619d8f53c31cd54c0b604eec3f7611c1" +reference = "https://github.com/open-telemetry/opentelemetry-proto/pull/635" +source_access = "auto" +built_at = "2026-11-16T16:09:42.245679+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:99c3c8d33dc8192932f3bb563292a1f08a1249a03a1344802c62d1cad2f5b8a8" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-03-28T17:13:29Z" +diff_format = "unified" +context_files = [ + "opentelemetry/proto/common/v1/common.proto", + "opentelemetry/proto/resource/v1/resource.proto", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 41 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.016586+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:2bc3e0fc8424891437eced2662477ff0dbc0eddd80a41de5db46f8109399ce58" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/open-telemetry__opentelemetry-proto-635/tests/capture.py b/tasks/open-telemetry__opentelemetry-proto-635/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-635/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/open-telemetry__opentelemetry-proto-635/tests/instruction.md b/tasks/open-telemetry__opentelemetry-proto-635/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a4b53a929166b1627b6728834dce5ff4cc7f8b60 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-635/tests/instruction.md @@ -0,0 +1,30 @@ +# Issue + +**Title:** Add EntityRef and use it in Resource. + +## Description + +As per [OTEP 264](https://github.com/open-telemetry/opentelemetry-specification/blob/main/oteps/entities/0264-resource-and-entities.md) - This is the proposal for representing "Entity" in OTLP. + +- Adds a new `EntityRef` message where an Entity is an object of interest in observability. + - Entity has a type (e.g. `host`, `k8s.pod`, `service`). + - Entity has a set of identifying attributes (these contribute to signal identity) + - Entity has a set of descriptive attirbutes (these are used to aide signal retreival/querying). + - Entity can be defined and versioned (e.g. semantic conventions via schema_url). +- Adds a new `entity_refs` field to `Resource` that allows distinguishing which key-value pairs in `Resource` come from which reported `Entity`. + +Please read the OTEP for details and rationale behind this protocol design. High level this meant to be: + +- Sufficient to represent entities +- Non-breaking for all OpenTelemetry users. + + +Prototypes using this protocol + +- java: +- collector: +- go: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `9d7c091a619d`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-635/tests/oracle.patch b/tasks/open-telemetry__opentelemetry-proto-635/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..01f76b74de23c4ae6673924d3ffb9d5f047961d3 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-635/tests/oracle.patch @@ -0,0 +1,59 @@ +diff --git a/opentelemetry/proto/common/v1/common.proto b/opentelemetry/proto/common/v1/common.proto +index ff8a21a..57c9f86 100644 +--- a/opentelemetry/proto/common/v1/common.proto ++++ b/opentelemetry/proto/common/v1/common.proto +@@ -79,3 +79,37 @@ message InstrumentationScope { + repeated KeyValue attributes = 3; + uint32 dropped_attributes_count = 4; + } ++ ++// A reference to an Entity. ++// Entity represents an object of interest associated with produced telemetry: e.g spans, metrics, profiles, or logs. ++// ++// Status: [Development] ++message EntityRef { ++ // The Schema URL, if known. This is the identifier of the Schema that the entity data ++ // is recorded in. To learn more about Schema URL see ++ // https://opentelemetry.io/docs/specs/otel/schemas/#schema-url ++ // ++ // This schema_url applies to the data in this message and to the Resource attributes ++ // referenced by id_keys and description_keys. ++ // TODO: discuss if we are happy with this somewhat complicated definition of what ++ // the schema_url applies to. ++ // ++ // This field obsoletes the schema_url field in ResourceMetrics/ResourceSpans/ResourceLogs. ++ string schema_url = 1; ++ ++ // Defines the type of the entity. MUST not change during the lifetime of the entity. ++ // For example: "service" or "host". This field is required and MUST not be empty ++ // for valid entities. ++ string type = 2; ++ ++ // Attribute Keys that identify the entity. ++ // MUST not change during the lifetime of the entity. The Id must contain at least one attribute. ++ // These keys MUST exist in the containing {message}.attributes. ++ repeated string id_keys = 3; ++ ++ // Descriptive (non-identifying) attribute keys of the entity. ++ // MAY change over the lifetime of the entity. MAY be empty. ++ // These attribute keys are not part of entity's identity. ++ // These keys MUST exist in the containing {message}.attributes. ++ repeated string description_keys = 4; ++} +\ No newline at end of file +diff --git a/opentelemetry/proto/resource/v1/resource.proto b/opentelemetry/proto/resource/v1/resource.proto +index 6637560..05d4456 100644 +--- a/opentelemetry/proto/resource/v1/resource.proto ++++ b/opentelemetry/proto/resource/v1/resource.proto +@@ -34,4 +34,11 @@ message Resource { + // dropped_attributes_count is the number of dropped attributes. If the value is 0, then + // no attributes were dropped. + uint32 dropped_attributes_count = 2; ++ ++ // Set of entities that participate in this Resource. ++ // ++ // Note: keys in the references MUST exist in attributes of this message. ++ // ++ // Status: [Development] ++ repeated opentelemetry.proto.common.v1.EntityRef entity_refs = 3; + } diff --git a/tasks/open-telemetry__opentelemetry-proto-635/tests/test.sh b/tasks/open-telemetry__opentelemetry-proto-635/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..ca121a6735b01443f67263aba64905f2882cabe9 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-635/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 9d7c091a619d8f53c31cd54c0b604eec3f7611c1 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/open-telemetry__opentelemetry-proto-635/tests/verifier.py b/tasks/open-telemetry__opentelemetry-proto-635/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-635/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/open-telemetry__opentelemetry-proto-637/environment/Dockerfile b/tasks/open-telemetry__opentelemetry-proto-637/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f1ba9bdbd785d17e843cdb33623b6c354368b9be --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-637/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/open-telemetry/opentelemetry-proto.git +WORKDIR /workspace +RUN git fetch --depth 1 origin e4fd4f681f583b1bdea4d375ad19ddc0dc1f2e9c 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard e4fd4f681f583b1bdea4d375ad19ddc0dc1f2e9c \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base e4fd4f681f583b1bdea4d375ad19ddc0dc1f2e9c \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/open-telemetry__opentelemetry-proto-637/instruction.md b/tasks/open-telemetry__opentelemetry-proto-637/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8433f2de9a8ddcb84158ca7db3e9f6d30497969a --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-637/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Remove comment on each service about keeping the RPC alive + +## Description + +Tigran explained this comment was likely a hold over from the OpenCensus protobufs which did use streaming RPC's. Unary RPC's, which are used by the OpenTelemetry protocol, can not be kept alive making the comment out of place. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e4fd4f681f58`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-637/solution/patch.diff b/tasks/open-telemetry__opentelemetry-proto-637/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..6426151e64ed5db6a5af946b50713c54c09d6f4c --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-637/solution/patch.diff @@ -0,0 +1,52 @@ +diff --git a/opentelemetry/proto/collector/logs/v1/logs_service.proto b/opentelemetry/proto/collector/logs/v1/logs_service.proto +index 8260d8a..8be5cf7 100644 +--- a/opentelemetry/proto/collector/logs/v1/logs_service.proto ++++ b/opentelemetry/proto/collector/logs/v1/logs_service.proto +@@ -28,8 +28,6 @@ option go_package = "go.opentelemetry.io/proto/otlp/collector/logs/v1"; + // OpenTelemetry and an collector, or between an collector and a central collector (in this + // case logs are sent/received to/from multiple Applications). + service LogsService { +- // For performance reasons, it is recommended to keep this RPC +- // alive for the entire life of the application. + rpc Export(ExportLogsServiceRequest) returns (ExportLogsServiceResponse) {} + } + +diff --git a/opentelemetry/proto/collector/metrics/v1/metrics_service.proto b/opentelemetry/proto/collector/metrics/v1/metrics_service.proto +index dd48f1a..bc02428 100644 +--- a/opentelemetry/proto/collector/metrics/v1/metrics_service.proto ++++ b/opentelemetry/proto/collector/metrics/v1/metrics_service.proto +@@ -28,8 +28,6 @@ option go_package = "go.opentelemetry.io/proto/otlp/collector/metrics/v1"; + // instrumented with OpenTelemetry and a collector, or between a collector and a + // central collector. + service MetricsService { +- // For performance reasons, it is recommended to keep this RPC +- // alive for the entire life of the application. + rpc Export(ExportMetricsServiceRequest) returns (ExportMetricsServiceResponse) {} + } + +diff --git a/opentelemetry/proto/collector/profiles/v1development/profiles_service.proto b/opentelemetry/proto/collector/profiles/v1development/profiles_service.proto +index ab2433e..64c3608 100644 +--- a/opentelemetry/proto/collector/profiles/v1development/profiles_service.proto ++++ b/opentelemetry/proto/collector/profiles/v1development/profiles_service.proto +@@ -27,8 +27,6 @@ option go_package = "go.opentelemetry.io/proto/otlp/collector/profiles/v1develop + // Service that can be used to push profiles between one Application instrumented with + // OpenTelemetry and a collector, or between a collector and a central collector. + service ProfilesService { +- // For performance reasons, it is recommended to keep this RPC +- // alive for the entire life of the application. + rpc Export(ExportProfilesServiceRequest) returns (ExportProfilesServiceResponse) {} + } + +diff --git a/opentelemetry/proto/collector/trace/v1/trace_service.proto b/opentelemetry/proto/collector/trace/v1/trace_service.proto +index d6fe67f..efbbedb 100644 +--- a/opentelemetry/proto/collector/trace/v1/trace_service.proto ++++ b/opentelemetry/proto/collector/trace/v1/trace_service.proto +@@ -28,8 +28,6 @@ option go_package = "go.opentelemetry.io/proto/otlp/collector/trace/v1"; + // OpenTelemetry and a collector, or between a collector and a central collector (in this + // case spans are sent/received to/from multiple Applications). + service TraceService { +- // For performance reasons, it is recommended to keep this RPC +- // alive for the entire life of the application. + rpc Export(ExportTraceServiceRequest) returns (ExportTraceServiceResponse) {} + } + diff --git a/tasks/open-telemetry__opentelemetry-proto-637/solution/solve.sh b/tasks/open-telemetry__opentelemetry-proto-637/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-637/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/open-telemetry__opentelemetry-proto-637/task.toml b/tasks/open-telemetry__opentelemetry-proto-637/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..918185e5240cc5e8ef9d75755f07d5f23562bcb9 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-637/task.toml @@ -0,0 +1,71 @@ +version = "1.0" + +[task] +name = "trending/open-telemetry__opentelemetry-proto-637" +description = "Remove comment on each service about keeping the RPC alive" + +[metadata] +difficulty = "small" +category = "bugfix" +keywords = [ + "opentelemetry-proto", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "open-telemetry/opentelemetry-proto" +ref = "e4fd4f681f583b1bdea4d375ad19ddc0dc1f2e9c" +reference = "https://github.com/open-telemetry/opentelemetry-proto/pull/637" +source_access = "auto" +built_at = "2026-11-16T16:09:42.244320+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:b7ea017143c5bf6c0d82b66ea8f2fde2999e3cf8f6c34db6bc72d6fc125cffd2" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-03-28T17:18:16Z" +diff_format = "unified" +context_files = [ + "opentelemetry/proto/collector/logs/v1/logs_service.proto", + "opentelemetry/proto/collector/metrics/v1/metrics_service.proto", + "opentelemetry/proto/collector/profiles/v1development/profiles_service.proto", + "opentelemetry/proto/collector/trace/v1/trace_service.proto", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 8 +difficulty = "small" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.017073+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:65e43192baee8d09f16bca728fda77ec1f37deb0a4ec9dd58071bb4bc4b63512" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/open-telemetry__opentelemetry-proto-637/tests/capture.py b/tasks/open-telemetry__opentelemetry-proto-637/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-637/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/open-telemetry__opentelemetry-proto-637/tests/instruction.md b/tasks/open-telemetry__opentelemetry-proto-637/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8433f2de9a8ddcb84158ca7db3e9f6d30497969a --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-637/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Remove comment on each service about keeping the RPC alive + +## Description + +Tigran explained this comment was likely a hold over from the OpenCensus protobufs which did use streaming RPC's. Unary RPC's, which are used by the OpenTelemetry protocol, can not be kept alive making the comment out of place. + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `e4fd4f681f58`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-637/tests/oracle.patch b/tasks/open-telemetry__opentelemetry-proto-637/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..6426151e64ed5db6a5af946b50713c54c09d6f4c --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-637/tests/oracle.patch @@ -0,0 +1,52 @@ +diff --git a/opentelemetry/proto/collector/logs/v1/logs_service.proto b/opentelemetry/proto/collector/logs/v1/logs_service.proto +index 8260d8a..8be5cf7 100644 +--- a/opentelemetry/proto/collector/logs/v1/logs_service.proto ++++ b/opentelemetry/proto/collector/logs/v1/logs_service.proto +@@ -28,8 +28,6 @@ option go_package = "go.opentelemetry.io/proto/otlp/collector/logs/v1"; + // OpenTelemetry and an collector, or between an collector and a central collector (in this + // case logs are sent/received to/from multiple Applications). + service LogsService { +- // For performance reasons, it is recommended to keep this RPC +- // alive for the entire life of the application. + rpc Export(ExportLogsServiceRequest) returns (ExportLogsServiceResponse) {} + } + +diff --git a/opentelemetry/proto/collector/metrics/v1/metrics_service.proto b/opentelemetry/proto/collector/metrics/v1/metrics_service.proto +index dd48f1a..bc02428 100644 +--- a/opentelemetry/proto/collector/metrics/v1/metrics_service.proto ++++ b/opentelemetry/proto/collector/metrics/v1/metrics_service.proto +@@ -28,8 +28,6 @@ option go_package = "go.opentelemetry.io/proto/otlp/collector/metrics/v1"; + // instrumented with OpenTelemetry and a collector, or between a collector and a + // central collector. + service MetricsService { +- // For performance reasons, it is recommended to keep this RPC +- // alive for the entire life of the application. + rpc Export(ExportMetricsServiceRequest) returns (ExportMetricsServiceResponse) {} + } + +diff --git a/opentelemetry/proto/collector/profiles/v1development/profiles_service.proto b/opentelemetry/proto/collector/profiles/v1development/profiles_service.proto +index ab2433e..64c3608 100644 +--- a/opentelemetry/proto/collector/profiles/v1development/profiles_service.proto ++++ b/opentelemetry/proto/collector/profiles/v1development/profiles_service.proto +@@ -27,8 +27,6 @@ option go_package = "go.opentelemetry.io/proto/otlp/collector/profiles/v1develop + // Service that can be used to push profiles between one Application instrumented with + // OpenTelemetry and a collector, or between a collector and a central collector. + service ProfilesService { +- // For performance reasons, it is recommended to keep this RPC +- // alive for the entire life of the application. + rpc Export(ExportProfilesServiceRequest) returns (ExportProfilesServiceResponse) {} + } + +diff --git a/opentelemetry/proto/collector/trace/v1/trace_service.proto b/opentelemetry/proto/collector/trace/v1/trace_service.proto +index d6fe67f..efbbedb 100644 +--- a/opentelemetry/proto/collector/trace/v1/trace_service.proto ++++ b/opentelemetry/proto/collector/trace/v1/trace_service.proto +@@ -28,8 +28,6 @@ option go_package = "go.opentelemetry.io/proto/otlp/collector/trace/v1"; + // OpenTelemetry and a collector, or between a collector and a central collector (in this + // case spans are sent/received to/from multiple Applications). + service TraceService { +- // For performance reasons, it is recommended to keep this RPC +- // alive for the entire life of the application. + rpc Export(ExportTraceServiceRequest) returns (ExportTraceServiceResponse) {} + } + diff --git a/tasks/open-telemetry__opentelemetry-proto-637/tests/test.sh b/tasks/open-telemetry__opentelemetry-proto-637/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c4f905650e56c18022703ae434d39a90904d9e88 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-637/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace e4fd4f681f583b1bdea4d375ad19ddc0dc1f2e9c > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/open-telemetry__opentelemetry-proto-637/tests/verifier.py b/tasks/open-telemetry__opentelemetry-proto-637/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-637/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/open-telemetry__opentelemetry-proto-641/environment/Dockerfile b/tasks/open-telemetry__opentelemetry-proto-641/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ad807aa5f3af81bacd65f73a979dd9f63e5f719f --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-641/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/open-telemetry/opentelemetry-proto.git +WORKDIR /workspace +RUN git fetch --depth 1 origin a46b66e47a8ca53ae2ac60b9d1b9828c1d5faea4 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard a46b66e47a8ca53ae2ac60b9d1b9828c1d5faea4 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base a46b66e47a8ca53ae2ac60b9d1b9828c1d5faea4 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/open-telemetry__opentelemetry-proto-641/instruction.md b/tasks/open-telemetry__opentelemetry-proto-641/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b10946c984c6da96b4392c3c7d975e3231ce8080 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-641/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Add ossf-scorecard scanning workflow + +## Description + +See for details + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a46b66e47a8c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-641/solution/patch.diff b/tasks/open-telemetry__opentelemetry-proto-641/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..4a2fa64672775052e021a5d13bfd743638fb267f --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-641/solution/patch.diff @@ -0,0 +1,53 @@ +diff --git a/.github/workflows/ossf-scorecard.yml b/.github/workflows/ossf-scorecard.yml +new file mode 100644 +index 0000000..c7fe64b +--- /dev/null ++++ b/.github/workflows/ossf-scorecard.yml +@@ -0,0 +1,47 @@ ++name: OSSF Scorecard ++ ++on: ++ push: ++ branches: ++ - main ++ schedule: ++ - cron: "13 4 * * 4" # once a week ++ workflow_dispatch: ++ ++permissions: read-all ++ ++jobs: ++ analysis: ++ runs-on: ubuntu-latest ++ permissions: ++ # Needed for Code scanning upload ++ security-events: write ++ # Needed for GitHub OIDC token if publish_results is true ++ id-token: write ++ steps: ++ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ with: ++ persist-credentials: false ++ ++ - uses: ossf/scorecard-action@f49aabe0b5af0936a0987cfb85d86b75731b0186 # v2.4.1 ++ with: ++ results_file: results.sarif ++ results_format: sarif ++ publish_results: true ++ ++ # Upload the results as artifacts (optional). Commenting out will disable ++ # uploads of run results in SARIF format to the repository Actions tab. ++ # https://docs.github.com/en/actions/advanced-guides/storing-workflow-data-as-artifacts ++ - name: "Upload artifact" ++ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 ++ with: ++ name: SARIF file ++ path: results.sarif ++ retention-days: 5 ++ ++ # Upload the results to GitHub's code scanning dashboard (optional). ++ # Commenting out will disable upload of results to your repo's Code Scanning dashboard ++ - name: "Upload to code-scanning" ++ uses: github/codeql-action/upload-sarif@5f8171a638ada777af81d42b55959a643bb29017 # v3.28.12 ++ with: ++ sarif_file: results.sarif diff --git a/tasks/open-telemetry__opentelemetry-proto-641/solution/solve.sh b/tasks/open-telemetry__opentelemetry-proto-641/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-641/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/open-telemetry__opentelemetry-proto-641/task.toml b/tasks/open-telemetry__opentelemetry-proto-641/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9d1a8e7ef01d44a21ae30dc0eb6ea2073f5f118d --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-641/task.toml @@ -0,0 +1,68 @@ +version = "1.0" + +[task] +name = "trending/open-telemetry__opentelemetry-proto-641" +description = "Add ossf-scorecard scanning workflow" + +[metadata] +difficulty = "medium" +category = "bugfix" +keywords = [ + "opentelemetry-proto", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "open-telemetry/opentelemetry-proto" +ref = "a46b66e47a8ca53ae2ac60b9d1b9828c1d5faea4" +reference = "https://github.com/open-telemetry/opentelemetry-proto/pull/641" +source_access = "auto" +built_at = "2026-11-16T16:09:42.243063+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:1203ccbcab8ae8b1170b968ef0784eec4cefef4c4b7aeec674eeb52a57b27fbf" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-04-07T20:34:47Z" +diff_format = "unified" +context_files = [ + ".github/workflows/ossf-scorecard.yml", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 47 +difficulty = "medium" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.017573+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:ab4c649fd1cc6d786891a8194fc2d1008204a995292aee08460335b8d1db1ce0" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/open-telemetry__opentelemetry-proto-641/tests/capture.py b/tasks/open-telemetry__opentelemetry-proto-641/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-641/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/open-telemetry__opentelemetry-proto-641/tests/instruction.md b/tasks/open-telemetry__opentelemetry-proto-641/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b10946c984c6da96b4392c3c7d975e3231ce8080 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-641/tests/instruction.md @@ -0,0 +1,11 @@ +# Issue + +**Title:** Add ossf-scorecard scanning workflow + +## Description + +See for details + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a46b66e47a8c`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-641/tests/oracle.patch b/tasks/open-telemetry__opentelemetry-proto-641/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..4a2fa64672775052e021a5d13bfd743638fb267f --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-641/tests/oracle.patch @@ -0,0 +1,53 @@ +diff --git a/.github/workflows/ossf-scorecard.yml b/.github/workflows/ossf-scorecard.yml +new file mode 100644 +index 0000000..c7fe64b +--- /dev/null ++++ b/.github/workflows/ossf-scorecard.yml +@@ -0,0 +1,47 @@ ++name: OSSF Scorecard ++ ++on: ++ push: ++ branches: ++ - main ++ schedule: ++ - cron: "13 4 * * 4" # once a week ++ workflow_dispatch: ++ ++permissions: read-all ++ ++jobs: ++ analysis: ++ runs-on: ubuntu-latest ++ permissions: ++ # Needed for Code scanning upload ++ security-events: write ++ # Needed for GitHub OIDC token if publish_results is true ++ id-token: write ++ steps: ++ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2 ++ with: ++ persist-credentials: false ++ ++ - uses: ossf/scorecard-action@f49aabe0b5af0936a0987cfb85d86b75731b0186 # v2.4.1 ++ with: ++ results_file: results.sarif ++ results_format: sarif ++ publish_results: true ++ ++ # Upload the results as artifacts (optional). Commenting out will disable ++ # uploads of run results in SARIF format to the repository Actions tab. ++ # https://docs.github.com/en/actions/advanced-guides/storing-workflow-data-as-artifacts ++ - name: "Upload artifact" ++ uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 ++ with: ++ name: SARIF file ++ path: results.sarif ++ retention-days: 5 ++ ++ # Upload the results to GitHub's code scanning dashboard (optional). ++ # Commenting out will disable upload of results to your repo's Code Scanning dashboard ++ - name: "Upload to code-scanning" ++ uses: github/codeql-action/upload-sarif@5f8171a638ada777af81d42b55959a643bb29017 # v3.28.12 ++ with: ++ sarif_file: results.sarif diff --git a/tasks/open-telemetry__opentelemetry-proto-641/tests/test.sh b/tasks/open-telemetry__opentelemetry-proto-641/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d1fc1969c14f278e40b8285054d7bcc06ac7e31 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-641/tests/test.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -uxo pipefail +SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)" +cd /workspace +mkdir -p /logs/verifier +rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json +CAPTURE_DIR="$(mktemp -d)" || exit 1 +trap 'rm -rf -- "$CAPTURE_DIR"' EXIT +if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace a46b66e47a8ca53ae2ac60b9d1b9828c1d5faea4 > "$CAPTURE_DIR/predicted.patch"; then + echo "0.0" > /logs/verifier/reward.txt + printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json + exit 0 +fi +rm -f /logs/verifier/predicted.patch +cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch +: 'START_VERIFY_OUTPUT' +if ! python3 -I "$SCRIPT_DIR/verifier.py" \ + "$SCRIPT_DIR/oracle.patch" \ + "$CAPTURE_DIR/predicted.patch" \ + "$SCRIPT_DIR/instruction.md"; then + rm -f /logs/verifier/reward.txt /logs/verifier/reward.json + printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json +fi +: 'END_VERIFY_OUTPUT' +exit 0 diff --git a/tasks/open-telemetry__opentelemetry-proto-641/tests/verifier.py b/tasks/open-telemetry__opentelemetry-proto-641/tests/verifier.py new file mode 100644 index 0000000000000000000000000000000000000000..6b463d818d3322d4bd2873b9183f71c6ecc44a2d --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-641/tests/verifier.py @@ -0,0 +1,737 @@ +"""In-container verifier for pr_diff tasks (6-component reward). + +This module is the **standalone verifier** that runs inside the task's +Docker container, NOT a helper used at generation time. Generation emits +its source as ``tests/verifier.py``. Harbor delivers it at verify time, +and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction. + +Reward = weighted sum of 6 components (5 deterministic + 1 required LLM): + + format_valid (0 or 1) — predicted parses as a unified diff (guard) + size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...) + catches "rampage through the codebase" + file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard — + symmetric penalty over-punishes extras) + region_overlap ([0, 1]) — predicted hunks overlap oracle hunks + (strongest spatial-localization signal) + similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only + (no free credit for context lines) + llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?" + Anthropic Haiku by default; any OpenAI- + compatible server via ``R2E_JUDGE_ENDPOINT``. + null when the judge is unavailable + (no key or model, network, unreadable + reply) → ungraded, no reward file; a + reply without a valid score (refusal, + content filter, empty, no "score") → a + graded 0 + +Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from +the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task +pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below). +Override per-task via ``task.toml.metadata`` or per-run via env vars +``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` / +``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they +reach the verifier container). + +Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model +(default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible +server (vLLM, Ollama, a gateway) and switches the request to +``/chat/completions`` with a bearer token from +``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted +servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default +route and is never sent to a custom endpoint. + +Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40 +when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a +charitable judge from inflating scores on wildly wrong-sized patches). + +Outputs (mirrors `_pr_runtime_verifier.py` after #75): + /logs/verifier/reward.txt — single float (Harbor reads this); + graded runs only + /logs/verifier/reward-details.json — full component breakdown + status + (structured diagnostics; Harbor's `reward.json` schema is flat-numeric- + only, so the breakdown goes to the `reward-details.json` sidecar which + Harbor renders under Verifier Logs → Rewards) + +Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``, +``urllib``, ``sys``. The same module is imported by the unit tests +under ``tests/test_pr_diff_verifier.py`` so the in-container behavior +stays in lockstep with what we test. +""" + +from __future__ import annotations + +import argparse +import difflib +import json +import math +import os +import re +import sys +import urllib.error +import urllib.request + +# --------------------------------------------------------------------------- +# Parsing helpers (shared by multiple components) +# --------------------------------------------------------------------------- + +_DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$") +_HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@") +_FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ") +_INDEX_RE = re.compile(r"^index ") + + +def file_paths(diff: str) -> set[str]: + """Return the set of ``b/`` paths touched by a unified diff.""" + paths: set[str] = set() + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + paths.add(m.group(2)) + return paths + + +def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]: + """For each touched file, return list of (start_line, end_line) ranges + on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``). + """ + out: dict[str, list[tuple[int, int]]] = {} + current_file: str | None = None + for line in diff.splitlines(): + m = _DIFF_HEADER_RE.match(line) + if m: + current_file = m.group(2) + out.setdefault(current_file, []) + continue + m = _HUNK_HEADER_RE.match(line) + if m and current_file is not None: + new_start = int(m.group(3)) + new_count = int(m.group(4) or "1") + end = new_start + max(new_count - 1, 0) + out[current_file].append((new_start, end)) + return out + + +def _normalize_changes_only(diff: str) -> list[str]: + """Return the +/- lines (the actual changes) for similarity scoring. + + Drops: + - ``diff --git`` / ``index abc..def`` metadata + - ``@@ ... @@`` hunk markers (volatile line numbers) + - context lines (no +/- prefix) — these are unchanged code, scoring + them inflates similarity for trivial patches + Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity + stays in the comparison; normalizes off the tab+timestamp suffix git + sometimes appends. + """ + out: list[str] = [] + for line in diff.splitlines(): + if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line): + continue + if _HUNK_HEADER_RE.match(line): + continue + if _FILE_MARKER_RE.match(line): + out.append(line.split("\t")[0].strip()) + continue + # +/- lines (actual changes) + if line.startswith("+") or line.startswith("-"): + out.append(line) + return out + + +# --------------------------------------------------------------------------- +# Reward components +# --------------------------------------------------------------------------- + + +def format_valid(predicted: str) -> float: + """1.0 if the predicted text looks like a unified diff; else 0.0. + + Requires both a ``diff --git`` header and at least one real +/- line + (not the ``---`` / ``+++`` file-marker lines). + """ + if not predicted.strip(): + return 0.0 + has_header = False + has_change = False + for line in predicted.splitlines(): + if _DIFF_HEADER_RE.match(line): + has_header = True + elif (line.startswith("+") or line.startswith("-")) and not line.startswith( + ("+++ ", "--- ") + ): + has_change = True + if has_header and has_change: + return 1.0 + return 0.0 + + +def file_targeting(oracle: str, predicted: str) -> float: + """F1 over the changed-file sets. + + Why F1 instead of Jaccard: + - Missing an oracle file (FN) is a *big* failure. + - Touching one unrelated extra file (FP) is a small one. + - Jaccard punishes both equally, which over-penalizes the agent + for any extra exploration. + - F1 weights TP twice, giving partial credit when the agent finds + most-but-not-all of the oracle files even with some noise. + + Returns 1.0 if both sides touch zero files (degenerate). + """ + o = file_paths(oracle) + p = file_paths(predicted) + if not o and not p: + return 1.0 + tp = len(o & p) + fn = len(o - p) + fp = len(p - o) + if tp == 0: + return 0.0 + # F1 = 2·TP / (2·TP + FN + FP) + return (2 * tp) / (2 * tp + fn + fp) + + +def _count_loc_changes(diff: str) -> int: + """Number of real +/- lines (excluding file-marker lines).""" + n = 0 + for line in diff.splitlines(): + if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")): + n += 1 + return n + + +def size_sanity(oracle: str, predicted: str) -> float: + """Penalize predicted patches that are wildly larger / smaller than the oracle. + + Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``. + Both empty → 1.0 (degenerate but well-defined). One empty → 0.0. + + This is the "don't rampage through the codebase" guard — a 200-line + diff for a 3-line oracle scores ~0.015 here even if every other + component looks OK. + """ + o_loc = _count_loc_changes(oracle) + p_loc = _count_loc_changes(predicted) + if o_loc == 0 and p_loc == 0: + return 1.0 + if o_loc == 0 or p_loc == 0: + return 0.0 + return min(o_loc, p_loc) / max(o_loc, p_loc) + + +def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float: + """For each oracle hunk, did the predicted diff edit a line within + ``slack_lines`` of that hunk in the same file? + + Returns the fraction of oracle hunks that have at least one matching + predicted hunk. ``slack_lines`` tolerates slight line-number drift + when git diff renders the predicted hunk at a different offset. + """ + o_ranges = hunk_ranges(oracle) + p_ranges = hunk_ranges(predicted) + total = sum(len(v) for v in o_ranges.values()) + if total == 0: + return 1.0 # oracle has no hunks (degenerate) + matched = 0 + for fname, ranges in o_ranges.items(): + p_in_file = p_ranges.get(fname, []) + for o_start, o_end in ranges: + for p_start, p_end in p_in_file: + # Interval overlap with slack — max(starts) <= min(ends) + slack + if max(o_start, p_start) <= min(o_end, p_end) + slack_lines: + matched += 1 + break + return matched / total + + +def similarity(oracle: str, predicted: str) -> float: + """SequenceMatcher ratio over +/- lines only. + + No free credit for context lines — fixes the v0.8.1 inflation where a + one-line fix scored ~0.7 just because the 3 context lines on either + side were "matched". + """ + if not predicted.strip(): + return 0.0 + o = _normalize_changes_only(oracle) + p = _normalize_changes_only(predicted) + if not o: + return 0.0 + # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000 + # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can + # run the verifier past Harbor's timeout. Above this many line pairs, + # fall back to difflib's popular-element heuristic, which stays fast. + exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS + return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio() + + +_SIMILARITY_EXACT_PAIRS = 400_000 + +# A predicted patch over 10x the oracle's changed lines is already a +# catastrophic size mismatch (size_sanity < 0.10). Past this floor such a +# patch is a graded 0 instead of being scored, so one huge file can't slow +# the verifier past its timeout and turn a failing episode into a dropped, +# ungraded one. The byte cap stops it from being read at all. +_MAX_PREDICTED_FACTOR = 10 +_MAX_PREDICTED_FLOOR_LOC = 1_000 +_MAX_PREDICTED_BYTES = 16 * 1024 * 1024 + + +def predicted_too_large(oracle: str, predicted: str) -> bool: + """Whether the predicted patch is too large to score (a graded 0).""" + limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC) + return _count_loc_changes(predicted) > limit + + +# --------------------------------------------------------------------------- +# LLM-as-judge (Anthropic Messages API, stdlib urllib) +# --------------------------------------------------------------------------- + + +_JUDGE_PROMPT = ( + "You are scoring a code-fix patch on whether it logically addresses the " + "described issue. Output a single JSON object: " + '{{"score": , "reasoning": "<<=30 words"}}.\n\n' + "DO NOT use the oracle to grade. Score on:\n" + " - Does the predicted diff touch code regions that could plausibly fix the issue?\n" + " - Is the change direction consistent with what the issue describes?\n" + " - Is it a real attempt (not boilerplate, not no-op)?\n\n" + "Issue:\n{instruction}\n\n" + "Oracle (reference fix for comparison only — don't grade on similarity to it):\n" + "{oracle}\n\n" + "Predicted:\n{predicted}\n\n" + "Return ONLY the JSON object." +) + + +_DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001" +_ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages" +# Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM / +# Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses. +_PLACEHOLDER_API_KEY = "EMPTY" + + +def llm_judge( + *, + instruction: str, + oracle: str, + predicted: str, + api_key: str, + model: str = _DEFAULT_JUDGE_MODEL, + timeout: int = 60, + endpoint: str | None = None, +) -> tuple[float | None, str]: + """Return ``(score, status)``. + + ``score`` is a float in [0, 1] on success, ``None`` on failure. + ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` / + ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` / + ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``. + ``output_limit`` means the judge exhausted its configured token budget + (ungraded, even if a partial answer contains a score). ``parse`` means + the provider's body isn't JSON or has the wrong shape (ungraded); a reply + with no usable text (refusal, content filter, empty) or no valid score is + ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never + increases the other weights. + + ``endpoint`` — base URL of an OpenAI-compatible server. When set, the + request goes to ``/chat/completions`` with ``api_key`` as a + bearer token, at temperature 0, and ``model`` must be given explicitly; + otherwise it goes to Anthropic's Messages API unchanged. + """ + if not api_key: + return None, "no_api_key" + if endpoint and not model: + return None, "no_judge_model" + if not predicted.strip(): + return 0.0, "empty_predicted" + + # Truncate hard so we don't blow up the prompt for big diffs + prompt = _JUDGE_PROMPT.format( + instruction=instruction[:4000], + oracle=oracle[:4000], + predicted=predicted[:4000], + ) + payload: dict = { + "model": model, + "max_tokens": 200, + "messages": [{"role": "user", "content": prompt}], + } + if endpoint: + # Small self-hosted models are noisy judges at their default sampling + # temperature (same input scoring 0.0 one call and 1.0 the next); pin + # them to greedy. The Anthropic route keeps its defaults — the weights + # were calibrated against them. + payload["temperature"] = 0 + url = endpoint.rstrip("/") + "/chat/completions" + headers = { + "authorization": f"Bearer {api_key}", + "content-type": "application/json", + } + else: + url = _ANTHROPIC_MESSAGES_URL + headers = { + "x-api-key": api_key, + "anthropic-version": "2023-06-01", + "content-type": "application/json", + } + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request(url, data=body, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + raw = resp.read().decode("utf-8") + except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError): + return None, "network" + + try: + response = json.loads(raw) + except json.JSONDecodeError: + return None, "parse" + # Provider-reported truncation is a grader capacity failure, not evidence + # that the submitted patch is wrong. Reasoning models can spend the entire + # output budget before producing visible text. Never grade a partial score. + if isinstance(response, dict): + choices = response.get("choices") + if endpoint: + if ( + isinstance(choices, list) + and choices + and isinstance(choices[0], dict) + and choices[0].get("finish_reason") == "length" + ): + return None, "output_limit" + elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}: + return None, "output_limit" + text = _judge_text(response, openai_compatible=bool(endpoint)) + if text is None: + return None, "parse" + + # Pull the first JSON object out of the model's response + m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL) + if not m: + return None, "missing_score" + try: + obj = json.loads(m.group(0)) + score = obj.get("score") + except (json.JSONDecodeError, ValueError, TypeError): + return None, "missing_score" + if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score): + return None, "invalid_score" + return float(score), "ok" + + +def _judge_text(payload: object, *, openai_compatible: bool) -> str | None: + """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape. + + A refusal or a content filter is a well-formed reply with no usable text. + The agent's patch is in the prompt, so it can provoke one: that is ``""``, + which grades 0, not ``None``, which leaves the run ungraded. + + Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and + ``content`` empty or holding partial text to discard. OpenAI-compatible: + ``message.content`` is null with a ``refusal`` string or + ``finish_reason: "content_filter"``. + """ + if not isinstance(payload, dict): + return None + if openai_compatible: + choices = payload.get("choices") + if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict): + return None + message = choices[0].get("message") + if not isinstance(message, dict): + return None + if message.get("refusal") or choices[0].get("finish_reason") == "content_filter": + return "" + content = message.get("content") + if content is None: + return "" + if isinstance(content, str): + return content + if isinstance(content, list): # content parts + return "".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and isinstance(part.get("text", ""), str) + ) + return None + content = payload.get("content") + if not isinstance(content, list): + return None + if payload.get("stop_reason") == "refusal": + return "" + return "".join( + block["text"] + for block in content + if isinstance(block, dict) + and block.get("type", "text") == "text" + and isinstance(block.get("text"), str) + ) + + +# --------------------------------------------------------------------------- +# Combination +# --------------------------------------------------------------------------- + + +# Judge replies the agent can provoke: its patch text is part of the judge +# prompt, so it can steer the answer away from a valid score. These are a +# graded 0. An unreadable provider envelope (`parse`), missing configuration, +# a disabled judge, transport errors and an exhausted judge output budget leave +# the evaluation ungraded. Truncation alone cannot establish an incorrect patch. +_JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"}) + + +def evaluation_status(judge_score: float | None, judge_status: str) -> str: + """`graded` when the judge scored or the agent can have caused its failure.""" + if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO: + return "graded" + return "ungraded" + + +def combine(components: dict[str, float | None], weights: dict[str, float]) -> float: + """Combine declared components, requiring a positively weighted judge. + + Without a judge score the result is 0. ``main`` records it as a graded 0 + when the agent can have caused the judge failure, and otherwise writes no + reward file, so Harbor reports the trial as VERIFIER_FAILED. + """ + if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None: + return 0.0 + if any(w > 0 and components.get(k) is None for k, w in weights.items()): + return 0.0 + return _weighted_mean(components, weights) + + +def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float: + available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None] + if not available: + return 0.0 + # Relative weights need not sum to one. Scale first so large finite + # overrides cannot overflow the numerator or denominator into NaN. + scale = max(w for _, w in available) + normalized = [(k, w / scale) for k, w in available] + return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized) + + +# --------------------------------------------------------------------------- +# Entry point (invoked by tests/test.sh inside the container) +# --------------------------------------------------------------------------- + + +# Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer +# analysis grounded in per-task component data): +# +# - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero +# discriminative signal — its 0.05 weight was pure dead weight. +# - similarity → 0.10: Pearson ~0.85 correlation with region_overlap. +# Carrying both at 0.20 double-counts positional accuracy and +# additionally penalizes legitimate alternative implementations. +# - llm_judge → 0.50: only component capturing semantic correctness +# independent of textual form; diverges informatively from +# similarity on cases like tokenizers (judge=0.72, sim=0.08). +# - region_overlap stays 0.20: strongest spatial-localization signal. +# - file_targeting → 0.12: leading indicator, less correlated with the +# rest than region/similarity are with each other. +# - size_sanity → 0.08: useful outlier detector for catastrophic +# over/under-generation (prettier=0.01, serde=0.08). +# +# Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00. +_DEFAULT_WEIGHTS = { + "format_valid": 0.00, + "size_sanity": 0.08, + "file_targeting": 0.12, + "region_overlap": 0.20, + "similarity": 0.10, + "llm_judge": 0.50, +} + +# Hard cap: when size_sanity < this threshold, clamp final reward to +# ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating +# the score on patches that are wildly the wrong size (catastrophic +# over- or under-generation). +_CATASTROPHIC_SIZE_THRESHOLD = 0.10 +_CATASTROPHIC_SIZE_CAP = 0.40 + + +def _read_weights_from_env() -> dict[str, float]: + """Override defaults via R2E_W_* env vars (set in container by harbor).""" + overrides = { + "format_valid": os.environ.get("R2E_W_FORMAT"), + "size_sanity": os.environ.get("R2E_W_SIZE"), + "file_targeting": os.environ.get("R2E_W_FILE"), + "region_overlap": os.environ.get("R2E_W_REGION"), + "similarity": os.environ.get("R2E_W_SIM"), + "llm_judge": os.environ.get("R2E_W_JUDGE"), + } + out = dict(_DEFAULT_WEIGHTS) + for k, v in overrides.items(): + if v is None: + continue + try: + value = float(v) + if math.isfinite(value) and value >= 0: + out[k] = value + except (TypeError, ValueError): + continue + return out + + +def _judge_config_from_env() -> tuple[str, str, str | None]: + """``(api_key, model, endpoint)`` for the judge, from the verifier env. + + With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY`` + (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to + the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a + self-hosted server won't have Haiku): when unset, ``model`` comes back + as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of + calling out. Without an endpoint the default Anthropic route is + unchanged. + """ + endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None + model = os.environ.get("R2E_JUDGE_MODEL", "").strip() + if endpoint: + api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY + return api_key, model, endpoint + return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("oracle") + parser.add_argument("predicted") + parser.add_argument("instruction") + parser.add_argument("--out-dir", default="/logs/verifier") + args = parser.parse_args(argv) + os.makedirs(args.out_dir, exist_ok=True) + # This run is the only authority on the reward: an earlier or planted + # reward file must not stand if this evaluation ends up ungraded. + for name in ("reward.txt", "reward.json"): + try: + os.unlink(os.path.join(args.out_dir, name)) + except FileNotFoundError: + pass + oracle = _read_or_empty(args.oracle) + try: + oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES + except OSError: + oversized = False + predicted = "" if oversized else _read_or_empty(args.predicted) + if oversized or predicted_too_large(oracle, predicted): + breakdown = { + "final_reward": 0.0, + "evaluation_status": "graded", + "eval_trustworthy": False, + "predicted_status": "predicted_too_large", + } + _write_outputs(args.out_dir, 0.0, breakdown) + return 0 + instruction = _read_or_empty(args.instruction) + api_key, judge_model, judge_endpoint = _judge_config_from_env() + + fv = format_valid(predicted) + ss = size_sanity(oracle, predicted) + ft = file_targeting(oracle, predicted) + ro = region_overlap(oracle, predicted) + sim = similarity(oracle, predicted) + weights = _read_weights_from_env() + if weights["llm_judge"] <= 0: + judge_score, judge_status = None, "disabled" + else: + judge_score, judge_status = llm_judge( + instruction=instruction, + oracle=oracle, + predicted=predicted, + api_key=api_key, + model=judge_model, + endpoint=judge_endpoint, + ) + + components: dict[str, float | None] = { + "format_valid": fv, + "size_sanity": ss, + "file_targeting": ft, + "region_overlap": ro, + "similarity": sim, + "llm_judge": judge_score, + } + final = combine(components, weights) + final = max(0.0, min(1.0, final)) + + # Hard cap on catastrophic size mismatches. Without this, a charitable + # judge can inflate the reward on patches that are dramatically the + # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge + # was lenient at 0.25 despite the patch being a near-no-op vs a + # 500-line oracle). The cap kicks in only at the extremes. + if ss < _CATASTROPHIC_SIZE_THRESHOLD: + final = min(final, _CATASTROPHIC_SIZE_CAP) + + status = evaluation_status(judge_score, judge_status) + breakdown = { + # No reward exists for an ungraded evaluation: null, not a placeholder 0. + "final_reward": round(final, 6) if status == "graded" else None, + "evaluation_status": status, + "eval_trustworthy": judge_score is not None, + "diagnostic_similarity": round( + _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}), + 6, + ), + "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()}, + "weights": {k: round(v, 6) for k, v in weights.items()}, + "judge_model": judge_model if judge_status == "ok" else None, + "judge_endpoint": judge_endpoint, + "judge_status": judge_status, + } + + _write_outputs(args.out_dir, final, breakdown) + return 0 + + +def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None: + # An ungraded evaluation writes no reward file. Harbor then raises + # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is + # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout + # instead of training on a 0. Harbor's job mean and pass@k still count the + # trial as 0, so evaluation stays fail-closed. + if breakdown["evaluation_status"] == "graded": + with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f: + f.write(f"{final:.6f}\n") + # Harbor's `reward.json` must be a flat map of floats/ints (spec, see + # ); our breakdown carries nested + # dicts, judge strings, and status strings, so it goes to the sidecar the + # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig) + # for `_pr_runtime_verifier.py`. + with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f: + json.dump(breakdown, f, indent=2) + + # Also print to stdout so harbor's log captures the breakdown + print(json.dumps(breakdown, indent=2)) + + +def _read_or_empty(path: str) -> str: + try: + with open(path, encoding="utf-8") as f: + return f.read() + except (OSError, UnicodeDecodeError): + return "" + + +if __name__ == "__main__": + sys.exit(main()) + + +__all__ = [ + "combine", + "file_paths", + "file_targeting", + "format_valid", + "hunk_ranges", + "llm_judge", + "main", + "predicted_too_large", + "region_overlap", + "similarity", + "size_sanity", +] diff --git a/tasks/open-telemetry__opentelemetry-proto-643/environment/Dockerfile b/tasks/open-telemetry__opentelemetry-proto-643/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..959f90755fd9a9c3d926459c6f0bcada02c52883 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-643/environment/Dockerfile @@ -0,0 +1,37 @@ +# Auto-generated by Repo2RLEnv pr_diff — 6-component reward env. +# Agent-agnostic: the agent (claude-code / openhands / codex / etc.) +# installs itself at run time via its harbor adapter. We only ship +# the source repo — the oracle + verifier arrive at verify time via +# tests/, never baked into the agent's image. +FROM python:3.12-slim +ARG GITHUB_TOKEN= +RUN apt-get update \ + && apt-get install -y --no-install-recommends git ca-certificates curl \ + && rm -rf /var/lib/apt/lists/* +RUN git config --global --add safe.directory /workspace \ + && git config --global init.defaultBranch main \ + && git config --global advice.detachedHead false +RUN if [ -n "$GITHUB_TOKEN" ]; then \ + git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + else \ + git clone --filter=blob:none https://github.com/open-telemetry/opentelemetry-proto.git /workspace; \ + fi \ + && git -C /workspace remote set-url origin https://github.com/open-telemetry/opentelemetry-proto.git +WORKDIR /workspace +RUN git fetch --depth 1 origin 3ee8e6aab7b5fcf2d183f40be55c0723dcc88ce8 2>/dev/null \ + || git fetch --unshallow origin 2>/dev/null || true +RUN git reset --hard 3ee8e6aab7b5fcf2d183f40be55c0723dcc88ce8 \ + && git clean -fdx -e .venv -e venv -e __pycache__ +RUN git checkout -q -B base 3ee8e6aab7b5fcf2d183f40be55c0723dcc88ce8 \ + && git remote remove origin 2>/dev/null || true +RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \ + && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \ + && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \ + && git reflog expire --expire=now --all 2>/dev/null || true \ + && git gc --prune=now 2>/dev/null || true +RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \ + git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \ + && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \ + && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \ + && touch "$P/scrub-$K.promisor" && git prune --expire=now; \ + fi diff --git a/tasks/open-telemetry__opentelemetry-proto-643/instruction.md b/tasks/open-telemetry__opentelemetry-proto-643/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2bd07cbfa7bf980ae8999e0a6d94a5dfccd63f8 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-643/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Stabilize event_name in LogRecord + +## Description + +Part of + +Stabilize `event_name` in `LogRecord` that was introduced in + +See also: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3ee8e6aab7b5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-643/solution/patch.diff b/tasks/open-telemetry__opentelemetry-proto-643/solution/patch.diff new file mode 100644 index 0000000000000000000000000000000000000000..a6555c7040dce9121790581ce36e827ed2fdcc43 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-643/solution/patch.diff @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index d5cd38f..963dc77 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -8,6 +8,8 @@ The full list of changes can be found in the compare view for the respective rel + + ### Changed + ++- logs: Stabilize `event_name` field in `LogRecord` message. [#643](https://github.com/open-telemetry/opentelemetry-proto/pull/643) ++ + ### Removed + + ## 1.5.0 - 2024-12-12 +diff --git a/opentelemetry/proto/logs/v1/logs.proto b/opentelemetry/proto/logs/v1/logs.proto +index 261d229..4fe1130 100644 +--- a/opentelemetry/proto/logs/v1/logs.proto ++++ b/opentelemetry/proto/logs/v1/logs.proto +@@ -221,7 +221,5 @@ message LogRecord { + // as an event. + // + // [Optional]. +- // +- // Status: [Development] + string event_name = 12; + } diff --git a/tasks/open-telemetry__opentelemetry-proto-643/solution/solve.sh b/tasks/open-telemetry__opentelemetry-proto-643/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..459bebbb86a693f2a14402d32c4cf646aa0fc4ac --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-643/solution/solve.sh @@ -0,0 +1,6 @@ +#!/bin/bash +set -euxo pipefail +cd /workspace +git config --global --add safe.directory /workspace +PATCH="$(dirname "$0")/patch.diff" +git apply --verbose --reject "$PATCH" diff --git a/tasks/open-telemetry__opentelemetry-proto-643/task.toml b/tasks/open-telemetry__opentelemetry-proto-643/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b8635536e522a8aee6e895bc6eb43c984141a83a --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-643/task.toml @@ -0,0 +1,69 @@ +version = "1.0" + +[task] +name = "trending/open-telemetry__opentelemetry-proto-643" +description = "Stabilize event_name in LogRecord" + +[metadata] +difficulty = "easy" +category = "bugfix" +keywords = [ + "opentelemetry-proto", + "pr_diff", +] + +[metadata.repo2env] +pipeline = "pr_diff" +pipeline_version = "0.3.0" +repo = "open-telemetry/opentelemetry-proto" +ref = "3ee8e6aab7b5fcf2d183f40be55c0723dcc88ce8" +reference = "https://github.com/open-telemetry/opentelemetry-proto/pull/643" +source_access = "auto" +built_at = "2026-11-16T16:09:42.241822+00:00" +reward_kinds = [ + "diff_similarity", +] +spec_version = "0.2.0" +content_hash = "sha256:2ead1515168d299c4e48c4c5d4254ed3850bc95b630647771b10a26c7339282c" + +[metadata.repo2env.pr_diff] +pr_merged_at = "2025-04-10T16:15:40Z" +diff_format = "unified" +context_files = [ + "CHANGELOG.md", + "opentelemetry/proto/logs/v1/logs.proto", +] +bootstrap_image = "python:3.12-slim" + +[metadata.repo2env.reward_calibration] +baseline_reward = 0.0 +loc_changed = 4 +difficulty = "trivial" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "unverified" +stage = "generation" +reason_codes = [ + "validation_not_run", +] +detail = "Generated task; validation has not been established." +provenance = "unknown" +evidence = [] + +[metadata.repo2env.reproducibility] +mode = "inline_dockerfile" +image_ref = "python:3.12-slim" +image_tag = "python:3.12-slim" +image_visibility = "public" +pushed_at = "2026-11-16T16:20:02.018038+00:00" +pushed_by = "scalingX" +inline_recipe_sha256 = "sha256:579642eb44b85bf249d162736d2c1c520038093d4ce9a4bc12572f786e99e016" +inline_recipe_lines = 37 +inline_recipe_source = "user_dockerfile" + +[agent] +timeout_sec = 1800.0 + +[verifier] +timeout_sec = 300.0 diff --git a/tasks/open-telemetry__opentelemetry-proto-643/tests/capture.py b/tasks/open-telemetry__opentelemetry-proto-643/tests/capture.py new file mode 100644 index 0000000000000000000000000000000000000000..026e0f358b0fa9564067c2e1f9b58cdf48f3f07a --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-643/tests/capture.py @@ -0,0 +1,96 @@ +"""Standalone PR-diff capture without executing workspace Git configuration. + +The emitted task uses a regular clone with a pinned base commit. Only its +object store is read: refs, index, config, hooks and replacement refs are not +used. This is a configuration boundary, not a sandbox for a malicious process +that can modify the verifier, binaries or object store while capture runs. +""" + +from __future__ import annotations + +import argparse +import json +import os +import re +import shutil +import subprocess +import sys +import tempfile +from pathlib import Path + + +def capture(workspace: Path, base_commit: str) -> bytes: + """Capture tracked and new files through a fresh private Git index.""" + if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit): + raise ValueError("Expected the task's pinned SHA-1 base commit") + objects = workspace.resolve() / ".git" / "objects" + if not objects.is_dir(): + raise ValueError("The task's cloned Git object store is missing") + git = shutil.which("git", path=os.defpath) + if git is None: + raise FileNotFoundError("System git is unavailable") + with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary: + private = Path(temporary) + # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs, + # system/global includes, user attributes, templates or credential env. + env = { + "PATH": os.defpath, + "HOME": temporary, + "XDG_CONFIG_HOME": temporary, + "GIT_CONFIG_NOSYSTEM": "1", + "GIT_CONFIG_GLOBAL": os.devnull, + "GIT_ATTR_NOSYSTEM": "1", + "GIT_NO_REPLACE_OBJECTS": "1", + "GIT_NO_LAZY_FETCH": "1", + "GIT_TERMINAL_PROMPT": "0", + "LC_ALL": "C", + } + subprocess.run( + [git, "init", "--quiet", "--template=", str(private / "repository")], + env=env, + cwd=private, + check=True, + capture_output=True, + timeout=60, + ) + env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False) + command = [ + git, + f"--git-dir={private / 'repository/.git'}", + f"--work-tree={workspace.resolve()}", + ] + + def run(*args: str) -> bytes: + return subprocess.run( + [*command, *args], + env=env, + cwd=workspace, + check=True, + capture_output=True, + timeout=60, + ).stdout + + run("read-tree", f"{base_commit}^{{tree}}") + # All filter drivers are undefined in the private configuration. The + # workspace's clean filters, fsmonitor and hooks cannot be invoked. + run("add", "--all", "--", ".") + return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("workspace", type=Path) + parser.add_argument("base_commit") + args = parser.parse_args(argv) + try: + patch = capture(args.workspace, args.base_commit) + except (OSError, ValueError, subprocess.SubprocessError) as exc: + # Do not echo child stderr: it may contain workspace-controlled data. + sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n") + return 1 + sys.stdout.buffer.write(patch) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/open-telemetry__opentelemetry-proto-643/tests/instruction.md b/tasks/open-telemetry__opentelemetry-proto-643/tests/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b2bd07cbfa7bf980ae8999e0a6d94a5dfccd63f8 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-643/tests/instruction.md @@ -0,0 +1,15 @@ +# Issue + +**Title:** Stabilize event_name in LogRecord + +## Description + +Part of + +Stabilize `event_name` in `LogRecord` that was introduced in + +See also: + +## Task + +Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `3ee8e6aab7b5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward. \ No newline at end of file diff --git a/tasks/open-telemetry__opentelemetry-proto-643/tests/oracle.patch b/tasks/open-telemetry__opentelemetry-proto-643/tests/oracle.patch new file mode 100644 index 0000000000000000000000000000000000000000..a6555c7040dce9121790581ce36e827ed2fdcc43 --- /dev/null +++ b/tasks/open-telemetry__opentelemetry-proto-643/tests/oracle.patch @@ -0,0 +1,25 @@ +diff --git a/CHANGELOG.md b/CHANGELOG.md +index d5cd38f..963dc77 100644 +--- a/CHANGELOG.md ++++ b/CHANGELOG.md +@@ -8,6 +8,8 @@ The full list of changes can be found in the compare view for the respective rel + + ### Changed + ++- logs: Stabilize `event_name` field in `LogRecord` message. [#643](https://github.com/open-telemetry/opentelemetry-proto/pull/643) ++ + ### Removed + + ## 1.5.0 - 2024-12-12 +diff --git a/opentelemetry/proto/logs/v1/logs.proto b/opentelemetry/proto/logs/v1/logs.proto +index 261d229..4fe1130 100644 +--- a/opentelemetry/proto/logs/v1/logs.proto ++++ b/opentelemetry/proto/logs/v1/logs.proto +@@ -221,7 +221,5 @@ message LogRecord { + // as an event. + // + // [Optional]. +- // +- // Status: [Development] + string event_name = 12; + }