scalingX commited on
Commit
1d11e0d
·
verified ·
1 Parent(s): b4c8ff2

Add 10000 GitHub Trending pr_diff environments (part 70)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/livewire__livewire-10625/tests/test.sh +25 -0
  2. tasks/livewire__livewire-10625/tests/verifier.py +737 -0
  3. tasks/livewire__livewire-10626/environment/Dockerfile +37 -0
  4. tasks/livewire__livewire-10626/instruction.md +73 -0
  5. tasks/livewire__livewire-10626/solution/patch.diff +225 -0
  6. tasks/livewire__livewire-10626/solution/solve.sh +6 -0
  7. tasks/livewire__livewire-10626/task.toml +70 -0
  8. tasks/livewire__livewire-10626/tests/capture.py +96 -0
  9. tasks/livewire__livewire-10626/tests/instruction.md +73 -0
  10. tasks/livewire__livewire-10626/tests/oracle.patch +225 -0
  11. tasks/livewire__livewire-10626/tests/test.sh +25 -0
  12. tasks/livewire__livewire-10626/tests/verifier.py +737 -0
  13. tasks/livewire__livewire-10628/environment/Dockerfile +37 -0
  14. tasks/livewire__livewire-10628/instruction.md +108 -0
  15. tasks/livewire__livewire-10628/solution/patch.diff +608 -0
  16. tasks/livewire__livewire-10628/solution/solve.sh +6 -0
  17. tasks/livewire__livewire-10628/task.toml +70 -0
  18. tasks/livewire__livewire-10628/tests/capture.py +96 -0
  19. tasks/livewire__livewire-10628/tests/instruction.md +108 -0
  20. tasks/livewire__livewire-10628/tests/oracle.patch +608 -0
  21. tasks/livewire__livewire-10628/tests/test.sh +25 -0
  22. tasks/livewire__livewire-10628/tests/verifier.py +737 -0
  23. tasks/livewire__livewire-10629/environment/Dockerfile +37 -0
  24. tasks/livewire__livewire-10629/instruction.md +70 -0
  25. tasks/livewire__livewire-10629/solution/patch.diff +121 -0
  26. tasks/livewire__livewire-10629/solution/solve.sh +6 -0
  27. tasks/livewire__livewire-10629/task.toml +69 -0
  28. tasks/livewire__livewire-10629/tests/capture.py +96 -0
  29. tasks/livewire__livewire-10629/tests/instruction.md +70 -0
  30. tasks/livewire__livewire-10629/tests/oracle.patch +121 -0
  31. tasks/livewire__livewire-10629/tests/test.sh +25 -0
  32. tasks/livewire__livewire-10629/tests/verifier.py +737 -0
  33. tasks/livewire__livewire-10630/environment/Dockerfile +37 -0
  34. tasks/livewire__livewire-10630/instruction.md +55 -0
  35. tasks/livewire__livewire-10630/solution/patch.diff +331 -0
  36. tasks/livewire__livewire-10630/solution/solve.sh +6 -0
  37. tasks/livewire__livewire-10630/task.toml +70 -0
  38. tasks/livewire__livewire-10630/tests/capture.py +96 -0
  39. tasks/livewire__livewire-10630/tests/instruction.md +55 -0
  40. tasks/livewire__livewire-10630/tests/oracle.patch +331 -0
  41. tasks/livewire__livewire-10630/tests/test.sh +25 -0
  42. tasks/livewire__livewire-10630/tests/verifier.py +737 -0
  43. tasks/livewire__livewire-10633/environment/Dockerfile +37 -0
  44. tasks/livewire__livewire-10633/instruction.md +66 -0
  45. tasks/livewire__livewire-10633/solution/patch.diff +593 -0
  46. tasks/livewire__livewire-10633/solution/solve.sh +6 -0
  47. tasks/livewire__livewire-10633/task.toml +71 -0
  48. tasks/livewire__livewire-10633/tests/capture.py +96 -0
  49. tasks/livewire__livewire-10633/tests/instruction.md +66 -0
  50. tasks/livewire__livewire-10633/tests/oracle.patch +593 -0
tasks/livewire__livewire-10625/tests/test.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uxo pipefail
3
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
4
+ cd /workspace
5
+ mkdir -p /logs/verifier
6
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json
7
+ CAPTURE_DIR="$(mktemp -d)" || exit 1
8
+ trap 'rm -rf -- "$CAPTURE_DIR"' EXIT
9
+ if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 16f4c122578411fd4f8613a1d3b8bb4f30d8b38f > "$CAPTURE_DIR/predicted.patch"; then
10
+ echo "0.0" > /logs/verifier/reward.txt
11
+ printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json
12
+ exit 0
13
+ fi
14
+ rm -f /logs/verifier/predicted.patch
15
+ cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch
16
+ : 'START_VERIFY_OUTPUT'
17
+ if ! python3 -I "$SCRIPT_DIR/verifier.py" \
18
+ "$SCRIPT_DIR/oracle.patch" \
19
+ "$CAPTURE_DIR/predicted.patch" \
20
+ "$SCRIPT_DIR/instruction.md"; then
21
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json
22
+ printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json
23
+ fi
24
+ : 'END_VERIFY_OUTPUT'
25
+ exit 0
tasks/livewire__livewire-10625/tests/verifier.py ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """In-container verifier for pr_diff tasks (6-component reward).
2
+
3
+ This module is the **standalone verifier** that runs inside the task's
4
+ Docker container, NOT a helper used at generation time. Generation emits
5
+ its source as ``tests/verifier.py``. Harbor delivers it at verify time,
6
+ and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
7
+
8
+ Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
9
+
10
+ format_valid (0 or 1) — predicted parses as a unified diff (guard)
11
+ size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...)
12
+ catches "rampage through the codebase"
13
+ file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard —
14
+ symmetric penalty over-punishes extras)
15
+ region_overlap ([0, 1]) — predicted hunks overlap oracle hunks
16
+ (strongest spatial-localization signal)
17
+ similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only
18
+ (no free credit for context lines)
19
+ llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?"
20
+ Anthropic Haiku by default; any OpenAI-
21
+ compatible server via ``R2E_JUDGE_ENDPOINT``.
22
+ null when the judge is unavailable
23
+ (no key or model, network, unreadable
24
+ reply) → ungraded, no reward file; a
25
+ reply without a valid score (refusal,
26
+ content filter, empty, no "score") → a
27
+ graded 0
28
+
29
+ Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from
30
+ the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task
31
+ pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).
32
+ Override per-task via ``task.toml.metadata`` or per-run via env vars
33
+ ``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /
34
+ ``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they
35
+ reach the verifier container).
36
+
37
+ Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model
38
+ (default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible
39
+ server (vLLM, Ollama, a gateway) and switches the request to
40
+ ``<endpoint>/chat/completions`` with a bearer token from
41
+ ``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted
42
+ servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default
43
+ route and is never sent to a custom endpoint.
44
+
45
+ Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40
46
+ when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a
47
+ charitable judge from inflating scores on wildly wrong-sized patches).
48
+
49
+ Outputs (mirrors `_pr_runtime_verifier.py` after #75):
50
+ /logs/verifier/reward.txt — single float (Harbor reads this);
51
+ graded runs only
52
+ /logs/verifier/reward-details.json — full component breakdown + status
53
+ (structured diagnostics; Harbor's `reward.json` schema is flat-numeric-
54
+ only, so the breakdown goes to the `reward-details.json` sidecar which
55
+ Harbor renders under Verifier Logs → Rewards)
56
+
57
+ Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,
58
+ ``urllib``, ``sys``. The same module is imported by the unit tests
59
+ under ``tests/test_pr_diff_verifier.py`` so the in-container behavior
60
+ stays in lockstep with what we test.
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import argparse
66
+ import difflib
67
+ import json
68
+ import math
69
+ import os
70
+ import re
71
+ import sys
72
+ import urllib.error
73
+ import urllib.request
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Parsing helpers (shared by multiple components)
77
+ # ---------------------------------------------------------------------------
78
+
79
+ _DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")
80
+ _HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
81
+ _FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")
82
+ _INDEX_RE = re.compile(r"^index ")
83
+
84
+
85
+ def file_paths(diff: str) -> set[str]:
86
+ """Return the set of ``b/<path>`` paths touched by a unified diff."""
87
+ paths: set[str] = set()
88
+ for line in diff.splitlines():
89
+ m = _DIFF_HEADER_RE.match(line)
90
+ if m:
91
+ paths.add(m.group(2))
92
+ return paths
93
+
94
+
95
+ def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]:
96
+ """For each touched file, return list of (start_line, end_line) ranges
97
+ on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``).
98
+ """
99
+ out: dict[str, list[tuple[int, int]]] = {}
100
+ current_file: str | None = None
101
+ for line in diff.splitlines():
102
+ m = _DIFF_HEADER_RE.match(line)
103
+ if m:
104
+ current_file = m.group(2)
105
+ out.setdefault(current_file, [])
106
+ continue
107
+ m = _HUNK_HEADER_RE.match(line)
108
+ if m and current_file is not None:
109
+ new_start = int(m.group(3))
110
+ new_count = int(m.group(4) or "1")
111
+ end = new_start + max(new_count - 1, 0)
112
+ out[current_file].append((new_start, end))
113
+ return out
114
+
115
+
116
+ def _normalize_changes_only(diff: str) -> list[str]:
117
+ """Return the +/- lines (the actual changes) for similarity scoring.
118
+
119
+ Drops:
120
+ - ``diff --git`` / ``index abc..def`` metadata
121
+ - ``@@ ... @@`` hunk markers (volatile line numbers)
122
+ - context lines (no +/- prefix) — these are unchanged code, scoring
123
+ them inflates similarity for trivial patches
124
+ Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity
125
+ stays in the comparison; normalizes off the tab+timestamp suffix git
126
+ sometimes appends.
127
+ """
128
+ out: list[str] = []
129
+ for line in diff.splitlines():
130
+ if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line):
131
+ continue
132
+ if _HUNK_HEADER_RE.match(line):
133
+ continue
134
+ if _FILE_MARKER_RE.match(line):
135
+ out.append(line.split("\t")[0].strip())
136
+ continue
137
+ # +/- lines (actual changes)
138
+ if line.startswith("+") or line.startswith("-"):
139
+ out.append(line)
140
+ return out
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Reward components
145
+ # ---------------------------------------------------------------------------
146
+
147
+
148
+ def format_valid(predicted: str) -> float:
149
+ """1.0 if the predicted text looks like a unified diff; else 0.0.
150
+
151
+ Requires both a ``diff --git`` header and at least one real +/- line
152
+ (not the ``---`` / ``+++`` file-marker lines).
153
+ """
154
+ if not predicted.strip():
155
+ return 0.0
156
+ has_header = False
157
+ has_change = False
158
+ for line in predicted.splitlines():
159
+ if _DIFF_HEADER_RE.match(line):
160
+ has_header = True
161
+ elif (line.startswith("+") or line.startswith("-")) and not line.startswith(
162
+ ("+++ ", "--- ")
163
+ ):
164
+ has_change = True
165
+ if has_header and has_change:
166
+ return 1.0
167
+ return 0.0
168
+
169
+
170
+ def file_targeting(oracle: str, predicted: str) -> float:
171
+ """F1 over the changed-file sets.
172
+
173
+ Why F1 instead of Jaccard:
174
+ - Missing an oracle file (FN) is a *big* failure.
175
+ - Touching one unrelated extra file (FP) is a small one.
176
+ - Jaccard punishes both equally, which over-penalizes the agent
177
+ for any extra exploration.
178
+ - F1 weights TP twice, giving partial credit when the agent finds
179
+ most-but-not-all of the oracle files even with some noise.
180
+
181
+ Returns 1.0 if both sides touch zero files (degenerate).
182
+ """
183
+ o = file_paths(oracle)
184
+ p = file_paths(predicted)
185
+ if not o and not p:
186
+ return 1.0
187
+ tp = len(o & p)
188
+ fn = len(o - p)
189
+ fp = len(p - o)
190
+ if tp == 0:
191
+ return 0.0
192
+ # F1 = 2·TP / (2·TP + FN + FP)
193
+ return (2 * tp) / (2 * tp + fn + fp)
194
+
195
+
196
+ def _count_loc_changes(diff: str) -> int:
197
+ """Number of real +/- lines (excluding file-marker lines)."""
198
+ n = 0
199
+ for line in diff.splitlines():
200
+ if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")):
201
+ n += 1
202
+ return n
203
+
204
+
205
+ def size_sanity(oracle: str, predicted: str) -> float:
206
+ """Penalize predicted patches that are wildly larger / smaller than the oracle.
207
+
208
+ Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``.
209
+ Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
210
+
211
+ This is the "don't rampage through the codebase" guard — a 200-line
212
+ diff for a 3-line oracle scores ~0.015 here even if every other
213
+ component looks OK.
214
+ """
215
+ o_loc = _count_loc_changes(oracle)
216
+ p_loc = _count_loc_changes(predicted)
217
+ if o_loc == 0 and p_loc == 0:
218
+ return 1.0
219
+ if o_loc == 0 or p_loc == 0:
220
+ return 0.0
221
+ return min(o_loc, p_loc) / max(o_loc, p_loc)
222
+
223
+
224
+ def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float:
225
+ """For each oracle hunk, did the predicted diff edit a line within
226
+ ``slack_lines`` of that hunk in the same file?
227
+
228
+ Returns the fraction of oracle hunks that have at least one matching
229
+ predicted hunk. ``slack_lines`` tolerates slight line-number drift
230
+ when git diff renders the predicted hunk at a different offset.
231
+ """
232
+ o_ranges = hunk_ranges(oracle)
233
+ p_ranges = hunk_ranges(predicted)
234
+ total = sum(len(v) for v in o_ranges.values())
235
+ if total == 0:
236
+ return 1.0 # oracle has no hunks (degenerate)
237
+ matched = 0
238
+ for fname, ranges in o_ranges.items():
239
+ p_in_file = p_ranges.get(fname, [])
240
+ for o_start, o_end in ranges:
241
+ for p_start, p_end in p_in_file:
242
+ # Interval overlap with slack — max(starts) <= min(ends) + slack
243
+ if max(o_start, p_start) <= min(o_end, p_end) + slack_lines:
244
+ matched += 1
245
+ break
246
+ return matched / total
247
+
248
+
249
+ def similarity(oracle: str, predicted: str) -> float:
250
+ """SequenceMatcher ratio over +/- lines only.
251
+
252
+ No free credit for context lines — fixes the v0.8.1 inflation where a
253
+ one-line fix scored ~0.7 just because the 3 context lines on either
254
+ side were "matched".
255
+ """
256
+ if not predicted.strip():
257
+ return 0.0
258
+ o = _normalize_changes_only(oracle)
259
+ p = _normalize_changes_only(predicted)
260
+ if not o:
261
+ return 0.0
262
+ # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000
263
+ # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can
264
+ # run the verifier past Harbor's timeout. Above this many line pairs,
265
+ # fall back to difflib's popular-element heuristic, which stays fast.
266
+ exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS
267
+ return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
268
+
269
+
270
+ _SIMILARITY_EXACT_PAIRS = 400_000
271
+
272
+ # A predicted patch over 10x the oracle's changed lines is already a
273
+ # catastrophic size mismatch (size_sanity < 0.10). Past this floor such a
274
+ # patch is a graded 0 instead of being scored, so one huge file can't slow
275
+ # the verifier past its timeout and turn a failing episode into a dropped,
276
+ # ungraded one. The byte cap stops it from being read at all.
277
+ _MAX_PREDICTED_FACTOR = 10
278
+ _MAX_PREDICTED_FLOOR_LOC = 1_000
279
+ _MAX_PREDICTED_BYTES = 16 * 1024 * 1024
280
+
281
+
282
+ def predicted_too_large(oracle: str, predicted: str) -> bool:
283
+ """Whether the predicted patch is too large to score (a graded 0)."""
284
+ limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC)
285
+ return _count_loc_changes(predicted) > limit
286
+
287
+
288
+ # ---------------------------------------------------------------------------
289
+ # LLM-as-judge (Anthropic Messages API, stdlib urllib)
290
+ # ---------------------------------------------------------------------------
291
+
292
+
293
+ _JUDGE_PROMPT = (
294
+ "You are scoring a code-fix patch on whether it logically addresses the "
295
+ "described issue. Output a single JSON object: "
296
+ '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n'
297
+ "DO NOT use the oracle to grade. Score on:\n"
298
+ " - Does the predicted diff touch code regions that could plausibly fix the issue?\n"
299
+ " - Is the change direction consistent with what the issue describes?\n"
300
+ " - Is it a real attempt (not boilerplate, not no-op)?\n\n"
301
+ "Issue:\n{instruction}\n\n"
302
+ "Oracle (reference fix for comparison only — don't grade on similarity to it):\n"
303
+ "{oracle}\n\n"
304
+ "Predicted:\n{predicted}\n\n"
305
+ "Return ONLY the JSON object."
306
+ )
307
+
308
+
309
+ _DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"
310
+ _ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"
311
+ # Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /
312
+ # Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses.
313
+ _PLACEHOLDER_API_KEY = "EMPTY"
314
+
315
+
316
+ def llm_judge(
317
+ *,
318
+ instruction: str,
319
+ oracle: str,
320
+ predicted: str,
321
+ api_key: str,
322
+ model: str = _DEFAULT_JUDGE_MODEL,
323
+ timeout: int = 60,
324
+ endpoint: str | None = None,
325
+ ) -> tuple[float | None, str]:
326
+ """Return ``(score, status)``.
327
+
328
+ ``score`` is a float in [0, 1] on success, ``None`` on failure.
329
+ ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` /
330
+ ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` /
331
+ ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``.
332
+ ``output_limit`` means the judge exhausted its configured token budget
333
+ (ungraded, even if a partial answer contains a score). ``parse`` means
334
+ the provider's body isn't JSON or has the wrong shape (ungraded); a reply
335
+ with no usable text (refusal, content filter, empty) or no valid score is
336
+ ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never
337
+ increases the other weights.
338
+
339
+ ``endpoint`` — base URL of an OpenAI-compatible server. When set, the
340
+ request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a
341
+ bearer token, at temperature 0, and ``model`` must be given explicitly;
342
+ otherwise it goes to Anthropic's Messages API unchanged.
343
+ """
344
+ if not api_key:
345
+ return None, "no_api_key"
346
+ if endpoint and not model:
347
+ return None, "no_judge_model"
348
+ if not predicted.strip():
349
+ return 0.0, "empty_predicted"
350
+
351
+ # Truncate hard so we don't blow up the prompt for big diffs
352
+ prompt = _JUDGE_PROMPT.format(
353
+ instruction=instruction[:4000],
354
+ oracle=oracle[:4000],
355
+ predicted=predicted[:4000],
356
+ )
357
+ payload: dict = {
358
+ "model": model,
359
+ "max_tokens": 200,
360
+ "messages": [{"role": "user", "content": prompt}],
361
+ }
362
+ if endpoint:
363
+ # Small self-hosted models are noisy judges at their default sampling
364
+ # temperature (same input scoring 0.0 one call and 1.0 the next); pin
365
+ # them to greedy. The Anthropic route keeps its defaults — the weights
366
+ # were calibrated against them.
367
+ payload["temperature"] = 0
368
+ url = endpoint.rstrip("/") + "/chat/completions"
369
+ headers = {
370
+ "authorization": f"Bearer {api_key}",
371
+ "content-type": "application/json",
372
+ }
373
+ else:
374
+ url = _ANTHROPIC_MESSAGES_URL
375
+ headers = {
376
+ "x-api-key": api_key,
377
+ "anthropic-version": "2023-06-01",
378
+ "content-type": "application/json",
379
+ }
380
+ body = json.dumps(payload).encode("utf-8")
381
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
382
+ try:
383
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
384
+ raw = resp.read().decode("utf-8")
385
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError):
386
+ return None, "network"
387
+
388
+ try:
389
+ response = json.loads(raw)
390
+ except json.JSONDecodeError:
391
+ return None, "parse"
392
+ # Provider-reported truncation is a grader capacity failure, not evidence
393
+ # that the submitted patch is wrong. Reasoning models can spend the entire
394
+ # output budget before producing visible text. Never grade a partial score.
395
+ if isinstance(response, dict):
396
+ choices = response.get("choices")
397
+ if endpoint:
398
+ if (
399
+ isinstance(choices, list)
400
+ and choices
401
+ and isinstance(choices[0], dict)
402
+ and choices[0].get("finish_reason") == "length"
403
+ ):
404
+ return None, "output_limit"
405
+ elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}:
406
+ return None, "output_limit"
407
+ text = _judge_text(response, openai_compatible=bool(endpoint))
408
+ if text is None:
409
+ return None, "parse"
410
+
411
+ # Pull the first JSON object out of the model's response
412
+ m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL)
413
+ if not m:
414
+ return None, "missing_score"
415
+ try:
416
+ obj = json.loads(m.group(0))
417
+ score = obj.get("score")
418
+ except (json.JSONDecodeError, ValueError, TypeError):
419
+ return None, "missing_score"
420
+ if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score):
421
+ return None, "invalid_score"
422
+ return float(score), "ok"
423
+
424
+
425
+ def _judge_text(payload: object, *, openai_compatible: bool) -> str | None:
426
+ """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
427
+
428
+ A refusal or a content filter is a well-formed reply with no usable text.
429
+ The agent's patch is in the prompt, so it can provoke one: that is ``""``,
430
+ which grades 0, not ``None``, which leaves the run ungraded.
431
+
432
+ Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and
433
+ ``content`` empty or holding partial text to discard. OpenAI-compatible:
434
+ ``message.content`` is null with a ``refusal`` string or
435
+ ``finish_reason: "content_filter"``.
436
+ """
437
+ if not isinstance(payload, dict):
438
+ return None
439
+ if openai_compatible:
440
+ choices = payload.get("choices")
441
+ if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
442
+ return None
443
+ message = choices[0].get("message")
444
+ if not isinstance(message, dict):
445
+ return None
446
+ if message.get("refusal") or choices[0].get("finish_reason") == "content_filter":
447
+ return ""
448
+ content = message.get("content")
449
+ if content is None:
450
+ return ""
451
+ if isinstance(content, str):
452
+ return content
453
+ if isinstance(content, list): # content parts
454
+ return "".join(
455
+ part.get("text", "")
456
+ for part in content
457
+ if isinstance(part, dict) and isinstance(part.get("text", ""), str)
458
+ )
459
+ return None
460
+ content = payload.get("content")
461
+ if not isinstance(content, list):
462
+ return None
463
+ if payload.get("stop_reason") == "refusal":
464
+ return ""
465
+ return "".join(
466
+ block["text"]
467
+ for block in content
468
+ if isinstance(block, dict)
469
+ and block.get("type", "text") == "text"
470
+ and isinstance(block.get("text"), str)
471
+ )
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # Combination
476
+ # ---------------------------------------------------------------------------
477
+
478
+
479
+ # Judge replies the agent can provoke: its patch text is part of the judge
480
+ # prompt, so it can steer the answer away from a valid score. These are a
481
+ # graded 0. An unreadable provider envelope (`parse`), missing configuration,
482
+ # a disabled judge, transport errors and an exhausted judge output budget leave
483
+ # the evaluation ungraded. Truncation alone cannot establish an incorrect patch.
484
+ _JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
485
+
486
+
487
+ def evaluation_status(judge_score: float | None, judge_status: str) -> str:
488
+ """`graded` when the judge scored or the agent can have caused its failure."""
489
+ if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO:
490
+ return "graded"
491
+ return "ungraded"
492
+
493
+
494
+ def combine(components: dict[str, float | None], weights: dict[str, float]) -> float:
495
+ """Combine declared components, requiring a positively weighted judge.
496
+
497
+ Without a judge score the result is 0. ``main`` records it as a graded 0
498
+ when the agent can have caused the judge failure, and otherwise writes no
499
+ reward file, so Harbor reports the trial as VERIFIER_FAILED.
500
+ """
501
+ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None:
502
+ return 0.0
503
+ if any(w > 0 and components.get(k) is None for k, w in weights.items()):
504
+ return 0.0
505
+ return _weighted_mean(components, weights)
506
+
507
+
508
+ def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float:
509
+ available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None]
510
+ if not available:
511
+ return 0.0
512
+ # Relative weights need not sum to one. Scale first so large finite
513
+ # overrides cannot overflow the numerator or denominator into NaN.
514
+ scale = max(w for _, w in available)
515
+ normalized = [(k, w / scale) for k, w in available]
516
+ return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
517
+
518
+
519
+ # ---------------------------------------------------------------------------
520
+ # Entry point (invoked by tests/test.sh inside the container)
521
+ # ---------------------------------------------------------------------------
522
+
523
+
524
+ # Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer
525
+ # analysis grounded in per-task component data):
526
+ #
527
+ # - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero
528
+ # discriminative signal — its 0.05 weight was pure dead weight.
529
+ # - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.
530
+ # Carrying both at 0.20 double-counts positional accuracy and
531
+ # additionally penalizes legitimate alternative implementations.
532
+ # - llm_judge → 0.50: only component capturing semantic correctness
533
+ # independent of textual form; diverges informatively from
534
+ # similarity on cases like tokenizers (judge=0.72, sim=0.08).
535
+ # - region_overlap stays 0.20: strongest spatial-localization signal.
536
+ # - file_targeting → 0.12: leading indicator, less correlated with the
537
+ # rest than region/similarity are with each other.
538
+ # - size_sanity → 0.08: useful outlier detector for catastrophic
539
+ # over/under-generation (prettier=0.01, serde=0.08).
540
+ #
541
+ # Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00.
542
+ _DEFAULT_WEIGHTS = {
543
+ "format_valid": 0.00,
544
+ "size_sanity": 0.08,
545
+ "file_targeting": 0.12,
546
+ "region_overlap": 0.20,
547
+ "similarity": 0.10,
548
+ "llm_judge": 0.50,
549
+ }
550
+
551
+ # Hard cap: when size_sanity < this threshold, clamp final reward to
552
+ # ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating
553
+ # the score on patches that are wildly the wrong size (catastrophic
554
+ # over- or under-generation).
555
+ _CATASTROPHIC_SIZE_THRESHOLD = 0.10
556
+ _CATASTROPHIC_SIZE_CAP = 0.40
557
+
558
+
559
+ def _read_weights_from_env() -> dict[str, float]:
560
+ """Override defaults via R2E_W_* env vars (set in container by harbor)."""
561
+ overrides = {
562
+ "format_valid": os.environ.get("R2E_W_FORMAT"),
563
+ "size_sanity": os.environ.get("R2E_W_SIZE"),
564
+ "file_targeting": os.environ.get("R2E_W_FILE"),
565
+ "region_overlap": os.environ.get("R2E_W_REGION"),
566
+ "similarity": os.environ.get("R2E_W_SIM"),
567
+ "llm_judge": os.environ.get("R2E_W_JUDGE"),
568
+ }
569
+ out = dict(_DEFAULT_WEIGHTS)
570
+ for k, v in overrides.items():
571
+ if v is None:
572
+ continue
573
+ try:
574
+ value = float(v)
575
+ if math.isfinite(value) and value >= 0:
576
+ out[k] = value
577
+ except (TypeError, ValueError):
578
+ continue
579
+ return out
580
+
581
+
582
+ def _judge_config_from_env() -> tuple[str, str, str | None]:
583
+ """``(api_key, model, endpoint)`` for the judge, from the verifier env.
584
+
585
+ With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY``
586
+ (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to
587
+ the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a
588
+ self-hosted server won't have Haiku): when unset, ``model`` comes back
589
+ as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of
590
+ calling out. Without an endpoint the default Anthropic route is
591
+ unchanged.
592
+ """
593
+ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None
594
+ model = os.environ.get("R2E_JUDGE_MODEL", "").strip()
595
+ if endpoint:
596
+ api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY
597
+ return api_key, model, endpoint
598
+ return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
599
+
600
+
601
+ def main(argv: list[str] | None = None) -> int:
602
+ parser = argparse.ArgumentParser(description=__doc__)
603
+ parser.add_argument("oracle")
604
+ parser.add_argument("predicted")
605
+ parser.add_argument("instruction")
606
+ parser.add_argument("--out-dir", default="/logs/verifier")
607
+ args = parser.parse_args(argv)
608
+ os.makedirs(args.out_dir, exist_ok=True)
609
+ # This run is the only authority on the reward: an earlier or planted
610
+ # reward file must not stand if this evaluation ends up ungraded.
611
+ for name in ("reward.txt", "reward.json"):
612
+ try:
613
+ os.unlink(os.path.join(args.out_dir, name))
614
+ except FileNotFoundError:
615
+ pass
616
+ oracle = _read_or_empty(args.oracle)
617
+ try:
618
+ oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES
619
+ except OSError:
620
+ oversized = False
621
+ predicted = "" if oversized else _read_or_empty(args.predicted)
622
+ if oversized or predicted_too_large(oracle, predicted):
623
+ breakdown = {
624
+ "final_reward": 0.0,
625
+ "evaluation_status": "graded",
626
+ "eval_trustworthy": False,
627
+ "predicted_status": "predicted_too_large",
628
+ }
629
+ _write_outputs(args.out_dir, 0.0, breakdown)
630
+ return 0
631
+ instruction = _read_or_empty(args.instruction)
632
+ api_key, judge_model, judge_endpoint = _judge_config_from_env()
633
+
634
+ fv = format_valid(predicted)
635
+ ss = size_sanity(oracle, predicted)
636
+ ft = file_targeting(oracle, predicted)
637
+ ro = region_overlap(oracle, predicted)
638
+ sim = similarity(oracle, predicted)
639
+ weights = _read_weights_from_env()
640
+ if weights["llm_judge"] <= 0:
641
+ judge_score, judge_status = None, "disabled"
642
+ else:
643
+ judge_score, judge_status = llm_judge(
644
+ instruction=instruction,
645
+ oracle=oracle,
646
+ predicted=predicted,
647
+ api_key=api_key,
648
+ model=judge_model,
649
+ endpoint=judge_endpoint,
650
+ )
651
+
652
+ components: dict[str, float | None] = {
653
+ "format_valid": fv,
654
+ "size_sanity": ss,
655
+ "file_targeting": ft,
656
+ "region_overlap": ro,
657
+ "similarity": sim,
658
+ "llm_judge": judge_score,
659
+ }
660
+ final = combine(components, weights)
661
+ final = max(0.0, min(1.0, final))
662
+
663
+ # Hard cap on catastrophic size mismatches. Without this, a charitable
664
+ # judge can inflate the reward on patches that are dramatically the
665
+ # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge
666
+ # was lenient at 0.25 despite the patch being a near-no-op vs a
667
+ # 500-line oracle). The cap kicks in only at the extremes.
668
+ if ss < _CATASTROPHIC_SIZE_THRESHOLD:
669
+ final = min(final, _CATASTROPHIC_SIZE_CAP)
670
+
671
+ status = evaluation_status(judge_score, judge_status)
672
+ breakdown = {
673
+ # No reward exists for an ungraded evaluation: null, not a placeholder 0.
674
+ "final_reward": round(final, 6) if status == "graded" else None,
675
+ "evaluation_status": status,
676
+ "eval_trustworthy": judge_score is not None,
677
+ "diagnostic_similarity": round(
678
+ _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}),
679
+ 6,
680
+ ),
681
+ "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()},
682
+ "weights": {k: round(v, 6) for k, v in weights.items()},
683
+ "judge_model": judge_model if judge_status == "ok" else None,
684
+ "judge_endpoint": judge_endpoint,
685
+ "judge_status": judge_status,
686
+ }
687
+
688
+ _write_outputs(args.out_dir, final, breakdown)
689
+ return 0
690
+
691
+
692
+ def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None:
693
+ # An ungraded evaluation writes no reward file. Harbor then raises
694
+ # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is
695
+ # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout
696
+ # instead of training on a 0. Harbor's job mean and pass@k still count the
697
+ # trial as 0, so evaluation stays fail-closed.
698
+ if breakdown["evaluation_status"] == "graded":
699
+ with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f:
700
+ f.write(f"{final:.6f}\n")
701
+ # Harbor's `reward.json` must be a flat map of floats/ints (spec, see
702
+ # <https://harborframework.com/docs/tasks>); our breakdown carries nested
703
+ # dicts, judge strings, and status strings, so it goes to the sidecar the
704
+ # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig)
705
+ # for `_pr_runtime_verifier.py`.
706
+ with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f:
707
+ json.dump(breakdown, f, indent=2)
708
+
709
+ # Also print to stdout so harbor's log captures the breakdown
710
+ print(json.dumps(breakdown, indent=2))
711
+
712
+
713
+ def _read_or_empty(path: str) -> str:
714
+ try:
715
+ with open(path, encoding="utf-8") as f:
716
+ return f.read()
717
+ except (OSError, UnicodeDecodeError):
718
+ return ""
719
+
720
+
721
+ if __name__ == "__main__":
722
+ sys.exit(main())
723
+
724
+
725
+ __all__ = [
726
+ "combine",
727
+ "file_paths",
728
+ "file_targeting",
729
+ "format_valid",
730
+ "hunk_ranges",
731
+ "llm_judge",
732
+ "main",
733
+ "predicted_too_large",
734
+ "region_overlap",
735
+ "similarity",
736
+ "size_sanity",
737
+ ]
tasks/livewire__livewire-10626/environment/Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.
2
+ # Agent-agnostic: the agent (claude-code / openhands / codex / etc.)
3
+ # installs itself at run time via its harbor adapter. We only ship
4
+ # the source repo — the oracle + verifier arrive at verify time via
5
+ # tests/, never baked into the agent's image.
6
+ FROM python:3.12-slim
7
+ ARG GITHUB_TOKEN=
8
+ RUN apt-get update \
9
+ && apt-get install -y --no-install-recommends git ca-certificates curl \
10
+ && rm -rf /var/lib/apt/lists/*
11
+ RUN git config --global --add safe.directory /workspace \
12
+ && git config --global init.defaultBranch main \
13
+ && git config --global advice.detachedHead false
14
+ RUN if [ -n "$GITHUB_TOKEN" ]; then \
15
+ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin db8815892bece057596cb5616ee15f6b42182bab 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard db8815892bece057596cb5616ee15f6b42182bab \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base db8815892bece057596cb5616ee15f6b42182bab \
26
+ && git remote remove origin 2>/dev/null || true
27
+ RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \
28
+ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \
29
+ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \
30
+ && git reflog expire --expire=now --all 2>/dev/null || true \
31
+ && git gc --prune=now 2>/dev/null || true
32
+ RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \
33
+ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \
34
+ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \
35
+ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \
36
+ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \
37
+ fi
tasks/livewire__livewire-10626/instruction.md ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** [4.x] Preserve islands after nested Blade directives
4
+
5
+ ## Description
6
+
7
+ Closes the compiler failure reported and diagnosed by @stebrl in #10624.
8
+
9
+ An island can be skipped during Livewire's island-only Blade pass when earlier directives share a nested-call prefix. The compiled view keeps an `@island` without Livewire's generated token, so every request fails with `IslandCompiler::getCachedPathFromToken(): Argument #1 ($token) must be of type string, null given`.
10
+
11
+ ## User experience
12
+
13
+ Given two ordinary directives before an island:
14
+
15
+ ```blade
16
+ @if (auth()->check())
17
+ first
18
+ @endif
19
+
20
+ @if (auth()->check() && request()->isMethod('get'))
21
+ second
22
+ @endif
23
+
24
+ @island
25
+ <div>...</div>
26
+ @endisland
27
+ ```
28
+
29
+ - **Actual:** the page deterministically returns 500 because the island token was dropped during compilation.
30
+ - **Expected:** directives before an island remain ordinary Blade and the island renders with its generated token.
31
+
32
+ ## Findings
33
+
34
+ - Confirmed demand is narrow: #10624 is the only exact report, from one application with two affected views. The failure is nevertheless production-fatal and uses supported syntax.
35
+ - The related #10277 / #10282 fixed nested parentheses on the island directive itself; this failure happens earlier, while foreign directives are passing through the island compiler.
36
+ - Laravel's `BladeCompiler::compileStatements()` repairs an initially unbalanced regex match with a search from the start of the template. Livewire's island pass returned foreign directives unchanged, leaving earlier identical prefixes visible to that repair. Blade could then reconstruct a later directive from an earlier one, advance its forward-only replacement offset beyond the island, and silently drop the tokenized replacement.
37
+ - Livewire has already fixed the same position-vs-value lookup class in a separate compiler path in #9921. Existing Blade-comment shielding in #9838 also provides local precedent for temporarily setting source aside.
38
+
39
+ ## Directions considered
40
+
41
+ - **Minimal:** mask the leading `@` in foreign directives during this pass. It fixes the reported case but a fixed marker can collide with authored content.
42
+ - **Maximal:** replace the hacked Blade compiler with a dedicated island parser and nested syntax tree. This removes the coupling entirely, but makes Livewire own a partial Blade lexer for escapes, comments, quotes, and malformed syntax.
43
+ - **Evaporative:** fix Laravel's global parenthesis-repair lookup upstream. Worth pursuing, but Livewire still needs a bridge across supported Laravel versions.
44
+ - **Userland:** hoist nested calls into variables/properties before the island. This works today, but is obscure, per-view, and not an appropriate framework answer.
45
+
46
+ This PR chooses the small compatibility bridge: every non-island directive is replaced with a collision-safe, per-pass placeholder, then restored byte-for-byte before islands are extracted. Escaped directives are also preserved until Blade's real compilation pass.
47
+
48
+ ## Built as working slices
49
+
50
+ Each commit is independently testable and evolves the same user-visible fix:
51
+
52
+ 1. **Skateboard — :** one obvious marker consumes foreign directives so Blade cannot skip the island; adds the browser regression.
53
+ 2. **Bicycle — :** stores and restores each foreign directive instead of globally replacing marker text.
54
+ 3. **Car — :** selects a placeholder prefix absent from the view and covers compiler fingerprints, custom directives, escaped directives, and marker-like authored content.
55
+
56
+ ## Verification
57
+
58
+ - Reproduced current `4.x` in a real Laravel app: HTTP 500 with the null-token exception.
59
+ - Verified the final branch in the same app: HTTP 200, `count: 0` rendered, generated island token present, no internal island/directive markers leaked.
60
+ - Full unit suite: 1,408 tests / 4,017 assertions passing (13 skipped, 3 incomplete).
61
+ - Full islands browser suite: 35 tests / 192 assertions passing.
62
+ - No documentation change: this restores existing documented behavior and introduces no public API.
63
+ - No new execution surface: foreign directives remain inert source during the island pre-pass and are restored exactly for Blade's normal compiler.
64
+
65
+ ## Follow-up
66
+
67
+ Laravel's position lookup should still be repaired upstream so other source-preserving compiler clients cannot hit the same class of failure. Livewire can remove this bridge once every supported Laravel line contains that fix.
68
+
69
+ A separate island-parser failure remains possible when raw or verbatim content contains an unbalanced `(` or a literal `@island`: this pre-pass calls `compileStatements()` directly, before Blade stores raw/verbatim blocks. It can produce the same missing-token symptom through a different path and should be handled separately rather than folded into this targeted fix.
70
+
71
+ ## Task
72
+
73
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `db8815892bec`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/livewire__livewire-10626/solution/patch.diff ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/src/Features/SupportIslands/BrowserTest.php b/src/Features/SupportIslands/BrowserTest.php
2
+ index b17c41ec..c4870c5e 100644
3
+ --- a/src/Features/SupportIslands/BrowserTest.php
4
+ +++ b/src/Features/SupportIslands/BrowserTest.php
5
+ @@ -2,6 +2,7 @@
6
+
7
+ namespace Livewire\Features\SupportIslands;
8
+
9
+ +use Illuminate\Support\Facades\Blade;
10
+ use Tests\BrowserTestCase;
11
+ use Livewire\Livewire;
12
+
13
+ @@ -47,6 +48,71 @@ class BrowserTest extends BrowserTestCase
14
+ ;
15
+ }
16
+
17
+ + public function test_island_after_repeated_nested_blade_directives()
18
+ + {
19
+ + Livewire::visit([new class extends \Livewire\Component {
20
+ + public $count = 0;
21
+ +
22
+ + public function render()
23
+ + {
24
+ + return <<<'HTML'
25
+ + <div>
26
+ + @if (auth()->check())
27
+ + first
28
+ + @endif
29
+ +
30
+ + @if (auth()->check() && request()->isMethod('get'))
31
+ + second
32
+ + @endif
33
+ +
34
+ + @island
35
+ + <div dusk="island">Count: {{ $count }}</div>
36
+ + @endisland
37
+ +
38
+ + @if (auth()->check())
39
+ + third
40
+ + @endif
41
+ +
42
+ + <div dusk="literal">[LIVEWIRE_DIRECTIVE_AT]</div>
43
+ + </div>
44
+ + HTML;
45
+ + }
46
+ + }])
47
+ + ->assertSeeIn('@island', 'Count: 0')
48
+ + ->assertSeeIn('@literal', '[LIVEWIRE_DIRECTIVE_AT]')
49
+ + ;
50
+ + }
51
+ +
52
+ + public function test_island_compilation_preserves_foreign_directives_and_marker_like_content()
53
+ + {
54
+ + Blade::directive('islandGreeting', fn ($expression) => '<div dusk="custom-directive">Hello from Blade</div>');
55
+ +
56
+ + Livewire::visit([new class extends \Livewire\Component {
57
+ + public function render()
58
+ + {
59
+ + return <<<'HTML'
60
+ + <div>
61
+ + @islandGreeting
62
+ +
63
+ + <div dusk="marker-like-content">[LIVEWIRE_DIRECTIVE:0]</div>
64
+ + <div dusk="escaped-directive">@@if (true)</div>
65
+ +
66
+ + @island
67
+ + <div dusk="island-with-foreign-directives">Island rendered</div>
68
+ + <div dusk="escaped-directive-inside-island">@@if (true)</div>
69
+ + @endisland
70
+ + </div>
71
+ + HTML;
72
+ + }
73
+ + }])
74
+ + ->assertSeeIn('@custom-directive', 'Hello from Blade')
75
+ + ->assertSeeIn('@marker-like-content', '[LIVEWIRE_DIRECTIVE:0]')
76
+ + ->assertSeeIn('@escaped-directive', '@if(true)')
77
+ + ->assertSeeIn('@island-with-foreign-directives', 'Island rendered')
78
+ + ->assertSeeIn('@escaped-directive-inside-island', '@if(true)')
79
+ + ;
80
+ + }
81
+ +
82
+ public function test_sibling_islands()
83
+ {
84
+ Livewire::visit([new class extends \Livewire\Component {
85
+ diff --git a/src/Features/SupportIslands/Compiler/IslandCompiler.php b/src/Features/SupportIslands/Compiler/IslandCompiler.php
86
+ index d38a0da5..ce7e2661 100644
87
+ --- a/src/Features/SupportIslands/Compiler/IslandCompiler.php
88
+ +++ b/src/Features/SupportIslands/Compiler/IslandCompiler.php
89
+ @@ -57,6 +57,8 @@ class IslandCompiler
90
+
91
+ $result = $compiler->compileStatementsMadePublic($contents);
92
+
93
+ + $result = $this->restoreSetAsideDirectives($result, $compiler->setAsideDirectives);
94
+ +
95
+ $result = $this->restoreBladeComments($result, $comments);
96
+
97
+ for ($i=$maxNestingLevel; $i >= $currentNestingLevel; $i--) {
98
+ @@ -210,41 +212,58 @@ PHP;
99
+ }, $contents);
100
+ }
101
+
102
+ + protected function restoreSetAsideDirectives(string $contents, array $directives): string
103
+ + {
104
+ + return strtr($contents, $directives);
105
+ + }
106
+ +
107
+ public function getHackedBladeCompiler()
108
+ {
109
+ $instance = new class (
110
+ app('files'),
111
+ rtrim(config('view.compiled'), '/\\') . '/livewire',
112
+ ) extends \Illuminate\View\Compilers\BladeCompiler {
113
+ + public array $setAsideDirectives = [];
114
+ +
115
+ + protected string $setAsideDirectivePrefix = '[LIVEWIRE_DIRECTIVE:';
116
+ +
117
+ /**
118
+ - * Make this method public...
119
+ + * Make statement compilation public and reserve a placeholder prefix
120
+ + * that does not collide with authored view content...
121
+ */
122
+ public function compileStatementsMadePublic($template)
123
+ {
124
+ + while (str_contains($template, $this->setAsideDirectivePrefix)) {
125
+ + $this->setAsideDirectivePrefix .= '_';
126
+ + }
127
+ +
128
+ return $this->compileStatements($template);
129
+ }
130
+
131
+ + protected function setAside($directive)
132
+ + {
133
+ + $placeholder = $this->setAsideDirectivePrefix . count($this->setAsideDirectives) . ']';
134
+ +
135
+ + $this->setAsideDirectives[$placeholder] = $directive;
136
+ +
137
+ + return $placeholder;
138
+ + }
139
+ +
140
+ /**
141
+ * Tweak this method to only process custom directives so we
142
+ * can restrict rendering solely to @island related directives...
143
+ */
144
+ protected function compileStatement($match)
145
+ {
146
+ - if (str_contains($match[1], '@')) {
147
+ - $match[0] = isset($match[3]) ? $match[1].$match[3] : $match[1];
148
+ - } elseif (isset($this->customDirectives[$match[1]])) {
149
+ - $match[0] = $this->callCustomDirective($match[1], Arr::get($match, 3));
150
+ - } elseif (method_exists($this, $method = 'compile'.ucfirst($match[1]))) {
151
+ - // Don't process through built-in directive methods...
152
+ - // $match[0] = $this->$method(Arr::get($match, 3));
153
+ -
154
+ - // Just return the original match...
155
+ - return $match[0];
156
+ - } else {
157
+ - return $match[0];
158
+ + if (isset($this->customDirectives[$match[1]])) {
159
+ + $compiled = $this->callCustomDirective($match[1], Arr::get($match, 3));
160
+ +
161
+ + return isset($match[3]) ? $compiled : $compiled.$match[2];
162
+ }
163
+
164
+ - return isset($match[3]) ? $match[0] : $match[0].$match[2];
165
+ + // Blade moves forward as it replaces statements, so foreign directives
166
+ + // must be consumed during this island-only pass and restored afterward...
167
+ + return $this->setAside($match[0]);
168
+ }
169
+ };
170
+
171
+ diff --git a/src/Features/SupportIslands/UnitTest.php b/src/Features/SupportIslands/UnitTest.php
172
+ index 26474b5e..9e37a50b 100644
173
+ --- a/src/Features/SupportIslands/UnitTest.php
174
+ +++ b/src/Features/SupportIslands/UnitTest.php
175
+ @@ -580,6 +580,50 @@ class UnitTest extends TestCase
176
+ ->assertSee('value: HELLO');
177
+ }
178
+
179
+ + public function test_island_keeps_its_token_when_a_directive_above_it_has_an_unbalanced_expression()
180
+ + {
181
+ + $compiledPath = sys_get_temp_dir() . '/laravel-island-offset-' . uniqid();
182
+ +
183
+ + config()->set('view.compiled', $compiledPath);
184
+ + app()->forgetInstance('livewire.compiler');
185
+ + app()->forgetInstance('livewire.factory');
186
+ +
187
+ + $compiled = IslandCompiler::compile(__FILE__, <<<'HTML'
188
+ + <div>
189
+ + @if (auth()->check())
190
+ + first
191
+ + @endif
192
+ +
193
+ + @if (auth()->check() && request()->isMethod('get'))
194
+ + second
195
+ + @endif
196
+ +
197
+ + @island(name: 'counter')
198
+ + @if (request()->isMethod('get'))
199
+ + <div>count: {{ $count }}</div>
200
+ + @endif
201
+ + @endisland
202
+ +
203
+ + @if (auth()->check())
204
+ + third
205
+ + @endif
206
+ + </div>
207
+ + HTML);
208
+ +
209
+ + $token = app('livewire.compiler')->cacheManager->getHash(__FILE__) . '-1';
210
+ + $cachedPath = IslandCompiler::getCachedPathFromToken($token);
211
+ +
212
+ + $this->assertStringContainsString("token: '{$token}'", $compiled);
213
+ + $this->assertStringNotContainsString('[ENDISLAND', $compiled);
214
+ + $this->assertStringNotContainsString('[LIVEWIRE_DIRECTIVE:', $compiled);
215
+ + $this->assertStringContainsString("@if (auth()->check() && request()->isMethod('get'))", $compiled);
216
+ + $this->assertFileExists($cachedPath);
217
+ + $this->assertStringContainsString("@if (request()->isMethod('get'))", File::get($cachedPath));
218
+ + $this->assertStringNotContainsString('[LIVEWIRE_DIRECTIVE:', File::get($cachedPath));
219
+ +
220
+ + File::deleteDirectory($compiledPath);
221
+ + }
222
+ +
223
+ public function test_island_tokens_are_stable_across_different_base_paths()
224
+ {
225
+ $path = '/resources/views/components/foo.blade.php';
tasks/livewire__livewire-10626/solution/solve.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euxo pipefail
3
+ cd /workspace
4
+ git config --global --add safe.directory /workspace
5
+ PATCH="$(dirname "$0")/patch.diff"
6
+ git apply --verbose --reject "$PATCH"
tasks/livewire__livewire-10626/task.toml ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/livewire__livewire-10626"
5
+ description = "[4.x] Preserve islands after nested Blade directives"
6
+
7
+ [metadata]
8
+ difficulty = "large"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "livewire",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "livewire/livewire"
19
+ ref = "db8815892bece057596cb5616ee15f6b42182bab"
20
+ reference = "https://github.com/livewire/livewire/pull/10626"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:51.558616+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:cea24ab1205cb84e7334d3543c18f890f08db9a0d0b1351be7003530a149ff28"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-08-29T14:02:22Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "src/Features/SupportIslands/BrowserTest.php",
34
+ "src/Features/SupportIslands/Compiler/IslandCompiler.php",
35
+ "src/Features/SupportIslands/UnitTest.php",
36
+ ]
37
+ bootstrap_image = "python:3.12-slim"
38
+
39
+ [metadata.repo2env.reward_calibration]
40
+ baseline_reward = 0.0
41
+ loc_changed = 157
42
+ difficulty = "large"
43
+
44
+ [metadata.repo2env.evaluation]
45
+ schema_version = "1"
46
+ status = "unverified"
47
+ stage = "generation"
48
+ reason_codes = [
49
+ "validation_not_run",
50
+ ]
51
+ detail = "Generated task; validation has not been established."
52
+ provenance = "unknown"
53
+ evidence = []
54
+
55
+ [metadata.repo2env.reproducibility]
56
+ mode = "inline_dockerfile"
57
+ image_ref = "python:3.12-slim"
58
+ image_tag = "python:3.12-slim"
59
+ image_visibility = "public"
60
+ pushed_at = "2026-11-16T16:20:01.366388+00:00"
61
+ pushed_by = "scalingX"
62
+ inline_recipe_sha256 = "sha256:213aef0bee925ab7039bf836902cfd18709931f36f4c04ee402909d61749364a"
63
+ inline_recipe_lines = 37
64
+ inline_recipe_source = "user_dockerfile"
65
+
66
+ [agent]
67
+ timeout_sec = 1800.0
68
+
69
+ [verifier]
70
+ timeout_sec = 300.0
tasks/livewire__livewire-10626/tests/capture.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone PR-diff capture without executing workspace Git configuration.
2
+
3
+ The emitted task uses a regular clone with a pinned base commit. Only its
4
+ object store is read: refs, index, config, hooks and replacement refs are not
5
+ used. This is a configuration boundary, not a sandbox for a malicious process
6
+ that can modify the verifier, binaries or object store while capture runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+
22
+ def capture(workspace: Path, base_commit: str) -> bytes:
23
+ """Capture tracked and new files through a fresh private Git index."""
24
+ if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit):
25
+ raise ValueError("Expected the task's pinned SHA-1 base commit")
26
+ objects = workspace.resolve() / ".git" / "objects"
27
+ if not objects.is_dir():
28
+ raise ValueError("The task's cloned Git object store is missing")
29
+ git = shutil.which("git", path=os.defpath)
30
+ if git is None:
31
+ raise FileNotFoundError("System git is unavailable")
32
+ with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary:
33
+ private = Path(temporary)
34
+ # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs,
35
+ # system/global includes, user attributes, templates or credential env.
36
+ env = {
37
+ "PATH": os.defpath,
38
+ "HOME": temporary,
39
+ "XDG_CONFIG_HOME": temporary,
40
+ "GIT_CONFIG_NOSYSTEM": "1",
41
+ "GIT_CONFIG_GLOBAL": os.devnull,
42
+ "GIT_ATTR_NOSYSTEM": "1",
43
+ "GIT_NO_REPLACE_OBJECTS": "1",
44
+ "GIT_NO_LAZY_FETCH": "1",
45
+ "GIT_TERMINAL_PROMPT": "0",
46
+ "LC_ALL": "C",
47
+ }
48
+ subprocess.run(
49
+ [git, "init", "--quiet", "--template=", str(private / "repository")],
50
+ env=env,
51
+ cwd=private,
52
+ check=True,
53
+ capture_output=True,
54
+ timeout=60,
55
+ )
56
+ env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False)
57
+ command = [
58
+ git,
59
+ f"--git-dir={private / 'repository/.git'}",
60
+ f"--work-tree={workspace.resolve()}",
61
+ ]
62
+
63
+ def run(*args: str) -> bytes:
64
+ return subprocess.run(
65
+ [*command, *args],
66
+ env=env,
67
+ cwd=workspace,
68
+ check=True,
69
+ capture_output=True,
70
+ timeout=60,
71
+ ).stdout
72
+
73
+ run("read-tree", f"{base_commit}^{{tree}}")
74
+ # All filter drivers are undefined in the private configuration. The
75
+ # workspace's clean filters, fsmonitor and hooks cannot be invoked.
76
+ run("add", "--all", "--", ".")
77
+ return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
78
+
79
+
80
+ def main(argv: list[str] | None = None) -> int:
81
+ parser = argparse.ArgumentParser(description=__doc__)
82
+ parser.add_argument("workspace", type=Path)
83
+ parser.add_argument("base_commit")
84
+ args = parser.parse_args(argv)
85
+ try:
86
+ patch = capture(args.workspace, args.base_commit)
87
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
88
+ # Do not echo child stderr: it may contain workspace-controlled data.
89
+ sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n")
90
+ return 1
91
+ sys.stdout.buffer.write(patch)
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
tasks/livewire__livewire-10626/tests/instruction.md ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** [4.x] Preserve islands after nested Blade directives
4
+
5
+ ## Description
6
+
7
+ Closes the compiler failure reported and diagnosed by @stebrl in #10624.
8
+
9
+ An island can be skipped during Livewire's island-only Blade pass when earlier directives share a nested-call prefix. The compiled view keeps an `@island` without Livewire's generated token, so every request fails with `IslandCompiler::getCachedPathFromToken(): Argument #1 ($token) must be of type string, null given`.
10
+
11
+ ## User experience
12
+
13
+ Given two ordinary directives before an island:
14
+
15
+ ```blade
16
+ @if (auth()->check())
17
+ first
18
+ @endif
19
+
20
+ @if (auth()->check() && request()->isMethod('get'))
21
+ second
22
+ @endif
23
+
24
+ @island
25
+ <div>...</div>
26
+ @endisland
27
+ ```
28
+
29
+ - **Actual:** the page deterministically returns 500 because the island token was dropped during compilation.
30
+ - **Expected:** directives before an island remain ordinary Blade and the island renders with its generated token.
31
+
32
+ ## Findings
33
+
34
+ - Confirmed demand is narrow: #10624 is the only exact report, from one application with two affected views. The failure is nevertheless production-fatal and uses supported syntax.
35
+ - The related #10277 / #10282 fixed nested parentheses on the island directive itself; this failure happens earlier, while foreign directives are passing through the island compiler.
36
+ - Laravel's `BladeCompiler::compileStatements()` repairs an initially unbalanced regex match with a search from the start of the template. Livewire's island pass returned foreign directives unchanged, leaving earlier identical prefixes visible to that repair. Blade could then reconstruct a later directive from an earlier one, advance its forward-only replacement offset beyond the island, and silently drop the tokenized replacement.
37
+ - Livewire has already fixed the same position-vs-value lookup class in a separate compiler path in #9921. Existing Blade-comment shielding in #9838 also provides local precedent for temporarily setting source aside.
38
+
39
+ ## Directions considered
40
+
41
+ - **Minimal:** mask the leading `@` in foreign directives during this pass. It fixes the reported case but a fixed marker can collide with authored content.
42
+ - **Maximal:** replace the hacked Blade compiler with a dedicated island parser and nested syntax tree. This removes the coupling entirely, but makes Livewire own a partial Blade lexer for escapes, comments, quotes, and malformed syntax.
43
+ - **Evaporative:** fix Laravel's global parenthesis-repair lookup upstream. Worth pursuing, but Livewire still needs a bridge across supported Laravel versions.
44
+ - **Userland:** hoist nested calls into variables/properties before the island. This works today, but is obscure, per-view, and not an appropriate framework answer.
45
+
46
+ This PR chooses the small compatibility bridge: every non-island directive is replaced with a collision-safe, per-pass placeholder, then restored byte-for-byte before islands are extracted. Escaped directives are also preserved until Blade's real compilation pass.
47
+
48
+ ## Built as working slices
49
+
50
+ Each commit is independently testable and evolves the same user-visible fix:
51
+
52
+ 1. **Skateboard — :** one obvious marker consumes foreign directives so Blade cannot skip the island; adds the browser regression.
53
+ 2. **Bicycle — :** stores and restores each foreign directive instead of globally replacing marker text.
54
+ 3. **Car — :** selects a placeholder prefix absent from the view and covers compiler fingerprints, custom directives, escaped directives, and marker-like authored content.
55
+
56
+ ## Verification
57
+
58
+ - Reproduced current `4.x` in a real Laravel app: HTTP 500 with the null-token exception.
59
+ - Verified the final branch in the same app: HTTP 200, `count: 0` rendered, generated island token present, no internal island/directive markers leaked.
60
+ - Full unit suite: 1,408 tests / 4,017 assertions passing (13 skipped, 3 incomplete).
61
+ - Full islands browser suite: 35 tests / 192 assertions passing.
62
+ - No documentation change: this restores existing documented behavior and introduces no public API.
63
+ - No new execution surface: foreign directives remain inert source during the island pre-pass and are restored exactly for Blade's normal compiler.
64
+
65
+ ## Follow-up
66
+
67
+ Laravel's position lookup should still be repaired upstream so other source-preserving compiler clients cannot hit the same class of failure. Livewire can remove this bridge once every supported Laravel line contains that fix.
68
+
69
+ A separate island-parser failure remains possible when raw or verbatim content contains an unbalanced `(` or a literal `@island`: this pre-pass calls `compileStatements()` directly, before Blade stores raw/verbatim blocks. It can produce the same missing-token symptom through a different path and should be handled separately rather than folded into this targeted fix.
70
+
71
+ ## Task
72
+
73
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `db8815892bec`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/livewire__livewire-10626/tests/oracle.patch ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/src/Features/SupportIslands/BrowserTest.php b/src/Features/SupportIslands/BrowserTest.php
2
+ index b17c41ec..c4870c5e 100644
3
+ --- a/src/Features/SupportIslands/BrowserTest.php
4
+ +++ b/src/Features/SupportIslands/BrowserTest.php
5
+ @@ -2,6 +2,7 @@
6
+
7
+ namespace Livewire\Features\SupportIslands;
8
+
9
+ +use Illuminate\Support\Facades\Blade;
10
+ use Tests\BrowserTestCase;
11
+ use Livewire\Livewire;
12
+
13
+ @@ -47,6 +48,71 @@ class BrowserTest extends BrowserTestCase
14
+ ;
15
+ }
16
+
17
+ + public function test_island_after_repeated_nested_blade_directives()
18
+ + {
19
+ + Livewire::visit([new class extends \Livewire\Component {
20
+ + public $count = 0;
21
+ +
22
+ + public function render()
23
+ + {
24
+ + return <<<'HTML'
25
+ + <div>
26
+ + @if (auth()->check())
27
+ + first
28
+ + @endif
29
+ +
30
+ + @if (auth()->check() && request()->isMethod('get'))
31
+ + second
32
+ + @endif
33
+ +
34
+ + @island
35
+ + <div dusk="island">Count: {{ $count }}</div>
36
+ + @endisland
37
+ +
38
+ + @if (auth()->check())
39
+ + third
40
+ + @endif
41
+ +
42
+ + <div dusk="literal">[LIVEWIRE_DIRECTIVE_AT]</div>
43
+ + </div>
44
+ + HTML;
45
+ + }
46
+ + }])
47
+ + ->assertSeeIn('@island', 'Count: 0')
48
+ + ->assertSeeIn('@literal', '[LIVEWIRE_DIRECTIVE_AT]')
49
+ + ;
50
+ + }
51
+ +
52
+ + public function test_island_compilation_preserves_foreign_directives_and_marker_like_content()
53
+ + {
54
+ + Blade::directive('islandGreeting', fn ($expression) => '<div dusk="custom-directive">Hello from Blade</div>');
55
+ +
56
+ + Livewire::visit([new class extends \Livewire\Component {
57
+ + public function render()
58
+ + {
59
+ + return <<<'HTML'
60
+ + <div>
61
+ + @islandGreeting
62
+ +
63
+ + <div dusk="marker-like-content">[LIVEWIRE_DIRECTIVE:0]</div>
64
+ + <div dusk="escaped-directive">@@if (true)</div>
65
+ +
66
+ + @island
67
+ + <div dusk="island-with-foreign-directives">Island rendered</div>
68
+ + <div dusk="escaped-directive-inside-island">@@if (true)</div>
69
+ + @endisland
70
+ + </div>
71
+ + HTML;
72
+ + }
73
+ + }])
74
+ + ->assertSeeIn('@custom-directive', 'Hello from Blade')
75
+ + ->assertSeeIn('@marker-like-content', '[LIVEWIRE_DIRECTIVE:0]')
76
+ + ->assertSeeIn('@escaped-directive', '@if(true)')
77
+ + ->assertSeeIn('@island-with-foreign-directives', 'Island rendered')
78
+ + ->assertSeeIn('@escaped-directive-inside-island', '@if(true)')
79
+ + ;
80
+ + }
81
+ +
82
+ public function test_sibling_islands()
83
+ {
84
+ Livewire::visit([new class extends \Livewire\Component {
85
+ diff --git a/src/Features/SupportIslands/Compiler/IslandCompiler.php b/src/Features/SupportIslands/Compiler/IslandCompiler.php
86
+ index d38a0da5..ce7e2661 100644
87
+ --- a/src/Features/SupportIslands/Compiler/IslandCompiler.php
88
+ +++ b/src/Features/SupportIslands/Compiler/IslandCompiler.php
89
+ @@ -57,6 +57,8 @@ class IslandCompiler
90
+
91
+ $result = $compiler->compileStatementsMadePublic($contents);
92
+
93
+ + $result = $this->restoreSetAsideDirectives($result, $compiler->setAsideDirectives);
94
+ +
95
+ $result = $this->restoreBladeComments($result, $comments);
96
+
97
+ for ($i=$maxNestingLevel; $i >= $currentNestingLevel; $i--) {
98
+ @@ -210,41 +212,58 @@ PHP;
99
+ }, $contents);
100
+ }
101
+
102
+ + protected function restoreSetAsideDirectives(string $contents, array $directives): string
103
+ + {
104
+ + return strtr($contents, $directives);
105
+ + }
106
+ +
107
+ public function getHackedBladeCompiler()
108
+ {
109
+ $instance = new class (
110
+ app('files'),
111
+ rtrim(config('view.compiled'), '/\\') . '/livewire',
112
+ ) extends \Illuminate\View\Compilers\BladeCompiler {
113
+ + public array $setAsideDirectives = [];
114
+ +
115
+ + protected string $setAsideDirectivePrefix = '[LIVEWIRE_DIRECTIVE:';
116
+ +
117
+ /**
118
+ - * Make this method public...
119
+ + * Make statement compilation public and reserve a placeholder prefix
120
+ + * that does not collide with authored view content...
121
+ */
122
+ public function compileStatementsMadePublic($template)
123
+ {
124
+ + while (str_contains($template, $this->setAsideDirectivePrefix)) {
125
+ + $this->setAsideDirectivePrefix .= '_';
126
+ + }
127
+ +
128
+ return $this->compileStatements($template);
129
+ }
130
+
131
+ + protected function setAside($directive)
132
+ + {
133
+ + $placeholder = $this->setAsideDirectivePrefix . count($this->setAsideDirectives) . ']';
134
+ +
135
+ + $this->setAsideDirectives[$placeholder] = $directive;
136
+ +
137
+ + return $placeholder;
138
+ + }
139
+ +
140
+ /**
141
+ * Tweak this method to only process custom directives so we
142
+ * can restrict rendering solely to @island related directives...
143
+ */
144
+ protected function compileStatement($match)
145
+ {
146
+ - if (str_contains($match[1], '@')) {
147
+ - $match[0] = isset($match[3]) ? $match[1].$match[3] : $match[1];
148
+ - } elseif (isset($this->customDirectives[$match[1]])) {
149
+ - $match[0] = $this->callCustomDirective($match[1], Arr::get($match, 3));
150
+ - } elseif (method_exists($this, $method = 'compile'.ucfirst($match[1]))) {
151
+ - // Don't process through built-in directive methods...
152
+ - // $match[0] = $this->$method(Arr::get($match, 3));
153
+ -
154
+ - // Just return the original match...
155
+ - return $match[0];
156
+ - } else {
157
+ - return $match[0];
158
+ + if (isset($this->customDirectives[$match[1]])) {
159
+ + $compiled = $this->callCustomDirective($match[1], Arr::get($match, 3));
160
+ +
161
+ + return isset($match[3]) ? $compiled : $compiled.$match[2];
162
+ }
163
+
164
+ - return isset($match[3]) ? $match[0] : $match[0].$match[2];
165
+ + // Blade moves forward as it replaces statements, so foreign directives
166
+ + // must be consumed during this island-only pass and restored afterward...
167
+ + return $this->setAside($match[0]);
168
+ }
169
+ };
170
+
171
+ diff --git a/src/Features/SupportIslands/UnitTest.php b/src/Features/SupportIslands/UnitTest.php
172
+ index 26474b5e..9e37a50b 100644
173
+ --- a/src/Features/SupportIslands/UnitTest.php
174
+ +++ b/src/Features/SupportIslands/UnitTest.php
175
+ @@ -580,6 +580,50 @@ class UnitTest extends TestCase
176
+ ->assertSee('value: HELLO');
177
+ }
178
+
179
+ + public function test_island_keeps_its_token_when_a_directive_above_it_has_an_unbalanced_expression()
180
+ + {
181
+ + $compiledPath = sys_get_temp_dir() . '/laravel-island-offset-' . uniqid();
182
+ +
183
+ + config()->set('view.compiled', $compiledPath);
184
+ + app()->forgetInstance('livewire.compiler');
185
+ + app()->forgetInstance('livewire.factory');
186
+ +
187
+ + $compiled = IslandCompiler::compile(__FILE__, <<<'HTML'
188
+ + <div>
189
+ + @if (auth()->check())
190
+ + first
191
+ + @endif
192
+ +
193
+ + @if (auth()->check() && request()->isMethod('get'))
194
+ + second
195
+ + @endif
196
+ +
197
+ + @island(name: 'counter')
198
+ + @if (request()->isMethod('get'))
199
+ + <div>count: {{ $count }}</div>
200
+ + @endif
201
+ + @endisland
202
+ +
203
+ + @if (auth()->check())
204
+ + third
205
+ + @endif
206
+ + </div>
207
+ + HTML);
208
+ +
209
+ + $token = app('livewire.compiler')->cacheManager->getHash(__FILE__) . '-1';
210
+ + $cachedPath = IslandCompiler::getCachedPathFromToken($token);
211
+ +
212
+ + $this->assertStringContainsString("token: '{$token}'", $compiled);
213
+ + $this->assertStringNotContainsString('[ENDISLAND', $compiled);
214
+ + $this->assertStringNotContainsString('[LIVEWIRE_DIRECTIVE:', $compiled);
215
+ + $this->assertStringContainsString("@if (auth()->check() && request()->isMethod('get'))", $compiled);
216
+ + $this->assertFileExists($cachedPath);
217
+ + $this->assertStringContainsString("@if (request()->isMethod('get'))", File::get($cachedPath));
218
+ + $this->assertStringNotContainsString('[LIVEWIRE_DIRECTIVE:', File::get($cachedPath));
219
+ +
220
+ + File::deleteDirectory($compiledPath);
221
+ + }
222
+ +
223
+ public function test_island_tokens_are_stable_across_different_base_paths()
224
+ {
225
+ $path = '/resources/views/components/foo.blade.php';
tasks/livewire__livewire-10626/tests/test.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uxo pipefail
3
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
4
+ cd /workspace
5
+ mkdir -p /logs/verifier
6
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json
7
+ CAPTURE_DIR="$(mktemp -d)" || exit 1
8
+ trap 'rm -rf -- "$CAPTURE_DIR"' EXIT
9
+ if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace db8815892bece057596cb5616ee15f6b42182bab > "$CAPTURE_DIR/predicted.patch"; then
10
+ echo "0.0" > /logs/verifier/reward.txt
11
+ printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json
12
+ exit 0
13
+ fi
14
+ rm -f /logs/verifier/predicted.patch
15
+ cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch
16
+ : 'START_VERIFY_OUTPUT'
17
+ if ! python3 -I "$SCRIPT_DIR/verifier.py" \
18
+ "$SCRIPT_DIR/oracle.patch" \
19
+ "$CAPTURE_DIR/predicted.patch" \
20
+ "$SCRIPT_DIR/instruction.md"; then
21
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json
22
+ printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json
23
+ fi
24
+ : 'END_VERIFY_OUTPUT'
25
+ exit 0
tasks/livewire__livewire-10626/tests/verifier.py ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """In-container verifier for pr_diff tasks (6-component reward).
2
+
3
+ This module is the **standalone verifier** that runs inside the task's
4
+ Docker container, NOT a helper used at generation time. Generation emits
5
+ its source as ``tests/verifier.py``. Harbor delivers it at verify time,
6
+ and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
7
+
8
+ Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
9
+
10
+ format_valid (0 or 1) — predicted parses as a unified diff (guard)
11
+ size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...)
12
+ catches "rampage through the codebase"
13
+ file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard —
14
+ symmetric penalty over-punishes extras)
15
+ region_overlap ([0, 1]) — predicted hunks overlap oracle hunks
16
+ (strongest spatial-localization signal)
17
+ similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only
18
+ (no free credit for context lines)
19
+ llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?"
20
+ Anthropic Haiku by default; any OpenAI-
21
+ compatible server via ``R2E_JUDGE_ENDPOINT``.
22
+ null when the judge is unavailable
23
+ (no key or model, network, unreadable
24
+ reply) → ungraded, no reward file; a
25
+ reply without a valid score (refusal,
26
+ content filter, empty, no "score") → a
27
+ graded 0
28
+
29
+ Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from
30
+ the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task
31
+ pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).
32
+ Override per-task via ``task.toml.metadata`` or per-run via env vars
33
+ ``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /
34
+ ``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they
35
+ reach the verifier container).
36
+
37
+ Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model
38
+ (default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible
39
+ server (vLLM, Ollama, a gateway) and switches the request to
40
+ ``<endpoint>/chat/completions`` with a bearer token from
41
+ ``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted
42
+ servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default
43
+ route and is never sent to a custom endpoint.
44
+
45
+ Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40
46
+ when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a
47
+ charitable judge from inflating scores on wildly wrong-sized patches).
48
+
49
+ Outputs (mirrors `_pr_runtime_verifier.py` after #75):
50
+ /logs/verifier/reward.txt — single float (Harbor reads this);
51
+ graded runs only
52
+ /logs/verifier/reward-details.json — full component breakdown + status
53
+ (structured diagnostics; Harbor's `reward.json` schema is flat-numeric-
54
+ only, so the breakdown goes to the `reward-details.json` sidecar which
55
+ Harbor renders under Verifier Logs → Rewards)
56
+
57
+ Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,
58
+ ``urllib``, ``sys``. The same module is imported by the unit tests
59
+ under ``tests/test_pr_diff_verifier.py`` so the in-container behavior
60
+ stays in lockstep with what we test.
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import argparse
66
+ import difflib
67
+ import json
68
+ import math
69
+ import os
70
+ import re
71
+ import sys
72
+ import urllib.error
73
+ import urllib.request
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Parsing helpers (shared by multiple components)
77
+ # ---------------------------------------------------------------------------
78
+
79
+ _DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")
80
+ _HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
81
+ _FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")
82
+ _INDEX_RE = re.compile(r"^index ")
83
+
84
+
85
+ def file_paths(diff: str) -> set[str]:
86
+ """Return the set of ``b/<path>`` paths touched by a unified diff."""
87
+ paths: set[str] = set()
88
+ for line in diff.splitlines():
89
+ m = _DIFF_HEADER_RE.match(line)
90
+ if m:
91
+ paths.add(m.group(2))
92
+ return paths
93
+
94
+
95
+ def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]:
96
+ """For each touched file, return list of (start_line, end_line) ranges
97
+ on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``).
98
+ """
99
+ out: dict[str, list[tuple[int, int]]] = {}
100
+ current_file: str | None = None
101
+ for line in diff.splitlines():
102
+ m = _DIFF_HEADER_RE.match(line)
103
+ if m:
104
+ current_file = m.group(2)
105
+ out.setdefault(current_file, [])
106
+ continue
107
+ m = _HUNK_HEADER_RE.match(line)
108
+ if m and current_file is not None:
109
+ new_start = int(m.group(3))
110
+ new_count = int(m.group(4) or "1")
111
+ end = new_start + max(new_count - 1, 0)
112
+ out[current_file].append((new_start, end))
113
+ return out
114
+
115
+
116
+ def _normalize_changes_only(diff: str) -> list[str]:
117
+ """Return the +/- lines (the actual changes) for similarity scoring.
118
+
119
+ Drops:
120
+ - ``diff --git`` / ``index abc..def`` metadata
121
+ - ``@@ ... @@`` hunk markers (volatile line numbers)
122
+ - context lines (no +/- prefix) — these are unchanged code, scoring
123
+ them inflates similarity for trivial patches
124
+ Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity
125
+ stays in the comparison; normalizes off the tab+timestamp suffix git
126
+ sometimes appends.
127
+ """
128
+ out: list[str] = []
129
+ for line in diff.splitlines():
130
+ if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line):
131
+ continue
132
+ if _HUNK_HEADER_RE.match(line):
133
+ continue
134
+ if _FILE_MARKER_RE.match(line):
135
+ out.append(line.split("\t")[0].strip())
136
+ continue
137
+ # +/- lines (actual changes)
138
+ if line.startswith("+") or line.startswith("-"):
139
+ out.append(line)
140
+ return out
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Reward components
145
+ # ---------------------------------------------------------------------------
146
+
147
+
148
+ def format_valid(predicted: str) -> float:
149
+ """1.0 if the predicted text looks like a unified diff; else 0.0.
150
+
151
+ Requires both a ``diff --git`` header and at least one real +/- line
152
+ (not the ``---`` / ``+++`` file-marker lines).
153
+ """
154
+ if not predicted.strip():
155
+ return 0.0
156
+ has_header = False
157
+ has_change = False
158
+ for line in predicted.splitlines():
159
+ if _DIFF_HEADER_RE.match(line):
160
+ has_header = True
161
+ elif (line.startswith("+") or line.startswith("-")) and not line.startswith(
162
+ ("+++ ", "--- ")
163
+ ):
164
+ has_change = True
165
+ if has_header and has_change:
166
+ return 1.0
167
+ return 0.0
168
+
169
+
170
+ def file_targeting(oracle: str, predicted: str) -> float:
171
+ """F1 over the changed-file sets.
172
+
173
+ Why F1 instead of Jaccard:
174
+ - Missing an oracle file (FN) is a *big* failure.
175
+ - Touching one unrelated extra file (FP) is a small one.
176
+ - Jaccard punishes both equally, which over-penalizes the agent
177
+ for any extra exploration.
178
+ - F1 weights TP twice, giving partial credit when the agent finds
179
+ most-but-not-all of the oracle files even with some noise.
180
+
181
+ Returns 1.0 if both sides touch zero files (degenerate).
182
+ """
183
+ o = file_paths(oracle)
184
+ p = file_paths(predicted)
185
+ if not o and not p:
186
+ return 1.0
187
+ tp = len(o & p)
188
+ fn = len(o - p)
189
+ fp = len(p - o)
190
+ if tp == 0:
191
+ return 0.0
192
+ # F1 = 2·TP / (2·TP + FN + FP)
193
+ return (2 * tp) / (2 * tp + fn + fp)
194
+
195
+
196
+ def _count_loc_changes(diff: str) -> int:
197
+ """Number of real +/- lines (excluding file-marker lines)."""
198
+ n = 0
199
+ for line in diff.splitlines():
200
+ if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")):
201
+ n += 1
202
+ return n
203
+
204
+
205
+ def size_sanity(oracle: str, predicted: str) -> float:
206
+ """Penalize predicted patches that are wildly larger / smaller than the oracle.
207
+
208
+ Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``.
209
+ Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
210
+
211
+ This is the "don't rampage through the codebase" guard — a 200-line
212
+ diff for a 3-line oracle scores ~0.015 here even if every other
213
+ component looks OK.
214
+ """
215
+ o_loc = _count_loc_changes(oracle)
216
+ p_loc = _count_loc_changes(predicted)
217
+ if o_loc == 0 and p_loc == 0:
218
+ return 1.0
219
+ if o_loc == 0 or p_loc == 0:
220
+ return 0.0
221
+ return min(o_loc, p_loc) / max(o_loc, p_loc)
222
+
223
+
224
+ def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float:
225
+ """For each oracle hunk, did the predicted diff edit a line within
226
+ ``slack_lines`` of that hunk in the same file?
227
+
228
+ Returns the fraction of oracle hunks that have at least one matching
229
+ predicted hunk. ``slack_lines`` tolerates slight line-number drift
230
+ when git diff renders the predicted hunk at a different offset.
231
+ """
232
+ o_ranges = hunk_ranges(oracle)
233
+ p_ranges = hunk_ranges(predicted)
234
+ total = sum(len(v) for v in o_ranges.values())
235
+ if total == 0:
236
+ return 1.0 # oracle has no hunks (degenerate)
237
+ matched = 0
238
+ for fname, ranges in o_ranges.items():
239
+ p_in_file = p_ranges.get(fname, [])
240
+ for o_start, o_end in ranges:
241
+ for p_start, p_end in p_in_file:
242
+ # Interval overlap with slack — max(starts) <= min(ends) + slack
243
+ if max(o_start, p_start) <= min(o_end, p_end) + slack_lines:
244
+ matched += 1
245
+ break
246
+ return matched / total
247
+
248
+
249
+ def similarity(oracle: str, predicted: str) -> float:
250
+ """SequenceMatcher ratio over +/- lines only.
251
+
252
+ No free credit for context lines — fixes the v0.8.1 inflation where a
253
+ one-line fix scored ~0.7 just because the 3 context lines on either
254
+ side were "matched".
255
+ """
256
+ if not predicted.strip():
257
+ return 0.0
258
+ o = _normalize_changes_only(oracle)
259
+ p = _normalize_changes_only(predicted)
260
+ if not o:
261
+ return 0.0
262
+ # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000
263
+ # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can
264
+ # run the verifier past Harbor's timeout. Above this many line pairs,
265
+ # fall back to difflib's popular-element heuristic, which stays fast.
266
+ exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS
267
+ return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
268
+
269
+
270
+ _SIMILARITY_EXACT_PAIRS = 400_000
271
+
272
+ # A predicted patch over 10x the oracle's changed lines is already a
273
+ # catastrophic size mismatch (size_sanity < 0.10). Past this floor such a
274
+ # patch is a graded 0 instead of being scored, so one huge file can't slow
275
+ # the verifier past its timeout and turn a failing episode into a dropped,
276
+ # ungraded one. The byte cap stops it from being read at all.
277
+ _MAX_PREDICTED_FACTOR = 10
278
+ _MAX_PREDICTED_FLOOR_LOC = 1_000
279
+ _MAX_PREDICTED_BYTES = 16 * 1024 * 1024
280
+
281
+
282
+ def predicted_too_large(oracle: str, predicted: str) -> bool:
283
+ """Whether the predicted patch is too large to score (a graded 0)."""
284
+ limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC)
285
+ return _count_loc_changes(predicted) > limit
286
+
287
+
288
+ # ---------------------------------------------------------------------------
289
+ # LLM-as-judge (Anthropic Messages API, stdlib urllib)
290
+ # ---------------------------------------------------------------------------
291
+
292
+
293
+ _JUDGE_PROMPT = (
294
+ "You are scoring a code-fix patch on whether it logically addresses the "
295
+ "described issue. Output a single JSON object: "
296
+ '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n'
297
+ "DO NOT use the oracle to grade. Score on:\n"
298
+ " - Does the predicted diff touch code regions that could plausibly fix the issue?\n"
299
+ " - Is the change direction consistent with what the issue describes?\n"
300
+ " - Is it a real attempt (not boilerplate, not no-op)?\n\n"
301
+ "Issue:\n{instruction}\n\n"
302
+ "Oracle (reference fix for comparison only — don't grade on similarity to it):\n"
303
+ "{oracle}\n\n"
304
+ "Predicted:\n{predicted}\n\n"
305
+ "Return ONLY the JSON object."
306
+ )
307
+
308
+
309
+ _DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"
310
+ _ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"
311
+ # Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /
312
+ # Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses.
313
+ _PLACEHOLDER_API_KEY = "EMPTY"
314
+
315
+
316
+ def llm_judge(
317
+ *,
318
+ instruction: str,
319
+ oracle: str,
320
+ predicted: str,
321
+ api_key: str,
322
+ model: str = _DEFAULT_JUDGE_MODEL,
323
+ timeout: int = 60,
324
+ endpoint: str | None = None,
325
+ ) -> tuple[float | None, str]:
326
+ """Return ``(score, status)``.
327
+
328
+ ``score`` is a float in [0, 1] on success, ``None`` on failure.
329
+ ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` /
330
+ ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` /
331
+ ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``.
332
+ ``output_limit`` means the judge exhausted its configured token budget
333
+ (ungraded, even if a partial answer contains a score). ``parse`` means
334
+ the provider's body isn't JSON or has the wrong shape (ungraded); a reply
335
+ with no usable text (refusal, content filter, empty) or no valid score is
336
+ ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never
337
+ increases the other weights.
338
+
339
+ ``endpoint`` — base URL of an OpenAI-compatible server. When set, the
340
+ request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a
341
+ bearer token, at temperature 0, and ``model`` must be given explicitly;
342
+ otherwise it goes to Anthropic's Messages API unchanged.
343
+ """
344
+ if not api_key:
345
+ return None, "no_api_key"
346
+ if endpoint and not model:
347
+ return None, "no_judge_model"
348
+ if not predicted.strip():
349
+ return 0.0, "empty_predicted"
350
+
351
+ # Truncate hard so we don't blow up the prompt for big diffs
352
+ prompt = _JUDGE_PROMPT.format(
353
+ instruction=instruction[:4000],
354
+ oracle=oracle[:4000],
355
+ predicted=predicted[:4000],
356
+ )
357
+ payload: dict = {
358
+ "model": model,
359
+ "max_tokens": 200,
360
+ "messages": [{"role": "user", "content": prompt}],
361
+ }
362
+ if endpoint:
363
+ # Small self-hosted models are noisy judges at their default sampling
364
+ # temperature (same input scoring 0.0 one call and 1.0 the next); pin
365
+ # them to greedy. The Anthropic route keeps its defaults — the weights
366
+ # were calibrated against them.
367
+ payload["temperature"] = 0
368
+ url = endpoint.rstrip("/") + "/chat/completions"
369
+ headers = {
370
+ "authorization": f"Bearer {api_key}",
371
+ "content-type": "application/json",
372
+ }
373
+ else:
374
+ url = _ANTHROPIC_MESSAGES_URL
375
+ headers = {
376
+ "x-api-key": api_key,
377
+ "anthropic-version": "2023-06-01",
378
+ "content-type": "application/json",
379
+ }
380
+ body = json.dumps(payload).encode("utf-8")
381
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
382
+ try:
383
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
384
+ raw = resp.read().decode("utf-8")
385
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError):
386
+ return None, "network"
387
+
388
+ try:
389
+ response = json.loads(raw)
390
+ except json.JSONDecodeError:
391
+ return None, "parse"
392
+ # Provider-reported truncation is a grader capacity failure, not evidence
393
+ # that the submitted patch is wrong. Reasoning models can spend the entire
394
+ # output budget before producing visible text. Never grade a partial score.
395
+ if isinstance(response, dict):
396
+ choices = response.get("choices")
397
+ if endpoint:
398
+ if (
399
+ isinstance(choices, list)
400
+ and choices
401
+ and isinstance(choices[0], dict)
402
+ and choices[0].get("finish_reason") == "length"
403
+ ):
404
+ return None, "output_limit"
405
+ elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}:
406
+ return None, "output_limit"
407
+ text = _judge_text(response, openai_compatible=bool(endpoint))
408
+ if text is None:
409
+ return None, "parse"
410
+
411
+ # Pull the first JSON object out of the model's response
412
+ m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL)
413
+ if not m:
414
+ return None, "missing_score"
415
+ try:
416
+ obj = json.loads(m.group(0))
417
+ score = obj.get("score")
418
+ except (json.JSONDecodeError, ValueError, TypeError):
419
+ return None, "missing_score"
420
+ if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score):
421
+ return None, "invalid_score"
422
+ return float(score), "ok"
423
+
424
+
425
+ def _judge_text(payload: object, *, openai_compatible: bool) -> str | None:
426
+ """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
427
+
428
+ A refusal or a content filter is a well-formed reply with no usable text.
429
+ The agent's patch is in the prompt, so it can provoke one: that is ``""``,
430
+ which grades 0, not ``None``, which leaves the run ungraded.
431
+
432
+ Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and
433
+ ``content`` empty or holding partial text to discard. OpenAI-compatible:
434
+ ``message.content`` is null with a ``refusal`` string or
435
+ ``finish_reason: "content_filter"``.
436
+ """
437
+ if not isinstance(payload, dict):
438
+ return None
439
+ if openai_compatible:
440
+ choices = payload.get("choices")
441
+ if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
442
+ return None
443
+ message = choices[0].get("message")
444
+ if not isinstance(message, dict):
445
+ return None
446
+ if message.get("refusal") or choices[0].get("finish_reason") == "content_filter":
447
+ return ""
448
+ content = message.get("content")
449
+ if content is None:
450
+ return ""
451
+ if isinstance(content, str):
452
+ return content
453
+ if isinstance(content, list): # content parts
454
+ return "".join(
455
+ part.get("text", "")
456
+ for part in content
457
+ if isinstance(part, dict) and isinstance(part.get("text", ""), str)
458
+ )
459
+ return None
460
+ content = payload.get("content")
461
+ if not isinstance(content, list):
462
+ return None
463
+ if payload.get("stop_reason") == "refusal":
464
+ return ""
465
+ return "".join(
466
+ block["text"]
467
+ for block in content
468
+ if isinstance(block, dict)
469
+ and block.get("type", "text") == "text"
470
+ and isinstance(block.get("text"), str)
471
+ )
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # Combination
476
+ # ---------------------------------------------------------------------------
477
+
478
+
479
+ # Judge replies the agent can provoke: its patch text is part of the judge
480
+ # prompt, so it can steer the answer away from a valid score. These are a
481
+ # graded 0. An unreadable provider envelope (`parse`), missing configuration,
482
+ # a disabled judge, transport errors and an exhausted judge output budget leave
483
+ # the evaluation ungraded. Truncation alone cannot establish an incorrect patch.
484
+ _JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
485
+
486
+
487
+ def evaluation_status(judge_score: float | None, judge_status: str) -> str:
488
+ """`graded` when the judge scored or the agent can have caused its failure."""
489
+ if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO:
490
+ return "graded"
491
+ return "ungraded"
492
+
493
+
494
+ def combine(components: dict[str, float | None], weights: dict[str, float]) -> float:
495
+ """Combine declared components, requiring a positively weighted judge.
496
+
497
+ Without a judge score the result is 0. ``main`` records it as a graded 0
498
+ when the agent can have caused the judge failure, and otherwise writes no
499
+ reward file, so Harbor reports the trial as VERIFIER_FAILED.
500
+ """
501
+ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None:
502
+ return 0.0
503
+ if any(w > 0 and components.get(k) is None for k, w in weights.items()):
504
+ return 0.0
505
+ return _weighted_mean(components, weights)
506
+
507
+
508
+ def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float:
509
+ available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None]
510
+ if not available:
511
+ return 0.0
512
+ # Relative weights need not sum to one. Scale first so large finite
513
+ # overrides cannot overflow the numerator or denominator into NaN.
514
+ scale = max(w for _, w in available)
515
+ normalized = [(k, w / scale) for k, w in available]
516
+ return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
517
+
518
+
519
+ # ---------------------------------------------------------------------------
520
+ # Entry point (invoked by tests/test.sh inside the container)
521
+ # ---------------------------------------------------------------------------
522
+
523
+
524
+ # Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer
525
+ # analysis grounded in per-task component data):
526
+ #
527
+ # - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero
528
+ # discriminative signal — its 0.05 weight was pure dead weight.
529
+ # - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.
530
+ # Carrying both at 0.20 double-counts positional accuracy and
531
+ # additionally penalizes legitimate alternative implementations.
532
+ # - llm_judge → 0.50: only component capturing semantic correctness
533
+ # independent of textual form; diverges informatively from
534
+ # similarity on cases like tokenizers (judge=0.72, sim=0.08).
535
+ # - region_overlap stays 0.20: strongest spatial-localization signal.
536
+ # - file_targeting → 0.12: leading indicator, less correlated with the
537
+ # rest than region/similarity are with each other.
538
+ # - size_sanity → 0.08: useful outlier detector for catastrophic
539
+ # over/under-generation (prettier=0.01, serde=0.08).
540
+ #
541
+ # Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00.
542
+ _DEFAULT_WEIGHTS = {
543
+ "format_valid": 0.00,
544
+ "size_sanity": 0.08,
545
+ "file_targeting": 0.12,
546
+ "region_overlap": 0.20,
547
+ "similarity": 0.10,
548
+ "llm_judge": 0.50,
549
+ }
550
+
551
+ # Hard cap: when size_sanity < this threshold, clamp final reward to
552
+ # ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating
553
+ # the score on patches that are wildly the wrong size (catastrophic
554
+ # over- or under-generation).
555
+ _CATASTROPHIC_SIZE_THRESHOLD = 0.10
556
+ _CATASTROPHIC_SIZE_CAP = 0.40
557
+
558
+
559
+ def _read_weights_from_env() -> dict[str, float]:
560
+ """Override defaults via R2E_W_* env vars (set in container by harbor)."""
561
+ overrides = {
562
+ "format_valid": os.environ.get("R2E_W_FORMAT"),
563
+ "size_sanity": os.environ.get("R2E_W_SIZE"),
564
+ "file_targeting": os.environ.get("R2E_W_FILE"),
565
+ "region_overlap": os.environ.get("R2E_W_REGION"),
566
+ "similarity": os.environ.get("R2E_W_SIM"),
567
+ "llm_judge": os.environ.get("R2E_W_JUDGE"),
568
+ }
569
+ out = dict(_DEFAULT_WEIGHTS)
570
+ for k, v in overrides.items():
571
+ if v is None:
572
+ continue
573
+ try:
574
+ value = float(v)
575
+ if math.isfinite(value) and value >= 0:
576
+ out[k] = value
577
+ except (TypeError, ValueError):
578
+ continue
579
+ return out
580
+
581
+
582
+ def _judge_config_from_env() -> tuple[str, str, str | None]:
583
+ """``(api_key, model, endpoint)`` for the judge, from the verifier env.
584
+
585
+ With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY``
586
+ (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to
587
+ the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a
588
+ self-hosted server won't have Haiku): when unset, ``model`` comes back
589
+ as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of
590
+ calling out. Without an endpoint the default Anthropic route is
591
+ unchanged.
592
+ """
593
+ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None
594
+ model = os.environ.get("R2E_JUDGE_MODEL", "").strip()
595
+ if endpoint:
596
+ api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY
597
+ return api_key, model, endpoint
598
+ return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
599
+
600
+
601
+ def main(argv: list[str] | None = None) -> int:
602
+ parser = argparse.ArgumentParser(description=__doc__)
603
+ parser.add_argument("oracle")
604
+ parser.add_argument("predicted")
605
+ parser.add_argument("instruction")
606
+ parser.add_argument("--out-dir", default="/logs/verifier")
607
+ args = parser.parse_args(argv)
608
+ os.makedirs(args.out_dir, exist_ok=True)
609
+ # This run is the only authority on the reward: an earlier or planted
610
+ # reward file must not stand if this evaluation ends up ungraded.
611
+ for name in ("reward.txt", "reward.json"):
612
+ try:
613
+ os.unlink(os.path.join(args.out_dir, name))
614
+ except FileNotFoundError:
615
+ pass
616
+ oracle = _read_or_empty(args.oracle)
617
+ try:
618
+ oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES
619
+ except OSError:
620
+ oversized = False
621
+ predicted = "" if oversized else _read_or_empty(args.predicted)
622
+ if oversized or predicted_too_large(oracle, predicted):
623
+ breakdown = {
624
+ "final_reward": 0.0,
625
+ "evaluation_status": "graded",
626
+ "eval_trustworthy": False,
627
+ "predicted_status": "predicted_too_large",
628
+ }
629
+ _write_outputs(args.out_dir, 0.0, breakdown)
630
+ return 0
631
+ instruction = _read_or_empty(args.instruction)
632
+ api_key, judge_model, judge_endpoint = _judge_config_from_env()
633
+
634
+ fv = format_valid(predicted)
635
+ ss = size_sanity(oracle, predicted)
636
+ ft = file_targeting(oracle, predicted)
637
+ ro = region_overlap(oracle, predicted)
638
+ sim = similarity(oracle, predicted)
639
+ weights = _read_weights_from_env()
640
+ if weights["llm_judge"] <= 0:
641
+ judge_score, judge_status = None, "disabled"
642
+ else:
643
+ judge_score, judge_status = llm_judge(
644
+ instruction=instruction,
645
+ oracle=oracle,
646
+ predicted=predicted,
647
+ api_key=api_key,
648
+ model=judge_model,
649
+ endpoint=judge_endpoint,
650
+ )
651
+
652
+ components: dict[str, float | None] = {
653
+ "format_valid": fv,
654
+ "size_sanity": ss,
655
+ "file_targeting": ft,
656
+ "region_overlap": ro,
657
+ "similarity": sim,
658
+ "llm_judge": judge_score,
659
+ }
660
+ final = combine(components, weights)
661
+ final = max(0.0, min(1.0, final))
662
+
663
+ # Hard cap on catastrophic size mismatches. Without this, a charitable
664
+ # judge can inflate the reward on patches that are dramatically the
665
+ # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge
666
+ # was lenient at 0.25 despite the patch being a near-no-op vs a
667
+ # 500-line oracle). The cap kicks in only at the extremes.
668
+ if ss < _CATASTROPHIC_SIZE_THRESHOLD:
669
+ final = min(final, _CATASTROPHIC_SIZE_CAP)
670
+
671
+ status = evaluation_status(judge_score, judge_status)
672
+ breakdown = {
673
+ # No reward exists for an ungraded evaluation: null, not a placeholder 0.
674
+ "final_reward": round(final, 6) if status == "graded" else None,
675
+ "evaluation_status": status,
676
+ "eval_trustworthy": judge_score is not None,
677
+ "diagnostic_similarity": round(
678
+ _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}),
679
+ 6,
680
+ ),
681
+ "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()},
682
+ "weights": {k: round(v, 6) for k, v in weights.items()},
683
+ "judge_model": judge_model if judge_status == "ok" else None,
684
+ "judge_endpoint": judge_endpoint,
685
+ "judge_status": judge_status,
686
+ }
687
+
688
+ _write_outputs(args.out_dir, final, breakdown)
689
+ return 0
690
+
691
+
692
+ def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None:
693
+ # An ungraded evaluation writes no reward file. Harbor then raises
694
+ # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is
695
+ # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout
696
+ # instead of training on a 0. Harbor's job mean and pass@k still count the
697
+ # trial as 0, so evaluation stays fail-closed.
698
+ if breakdown["evaluation_status"] == "graded":
699
+ with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f:
700
+ f.write(f"{final:.6f}\n")
701
+ # Harbor's `reward.json` must be a flat map of floats/ints (spec, see
702
+ # <https://harborframework.com/docs/tasks>); our breakdown carries nested
703
+ # dicts, judge strings, and status strings, so it goes to the sidecar the
704
+ # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig)
705
+ # for `_pr_runtime_verifier.py`.
706
+ with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f:
707
+ json.dump(breakdown, f, indent=2)
708
+
709
+ # Also print to stdout so harbor's log captures the breakdown
710
+ print(json.dumps(breakdown, indent=2))
711
+
712
+
713
+ def _read_or_empty(path: str) -> str:
714
+ try:
715
+ with open(path, encoding="utf-8") as f:
716
+ return f.read()
717
+ except (OSError, UnicodeDecodeError):
718
+ return ""
719
+
720
+
721
+ if __name__ == "__main__":
722
+ sys.exit(main())
723
+
724
+
725
+ __all__ = [
726
+ "combine",
727
+ "file_paths",
728
+ "file_targeting",
729
+ "format_valid",
730
+ "hunk_ranges",
731
+ "llm_judge",
732
+ "main",
733
+ "predicted_too_large",
734
+ "region_overlap",
735
+ "similarity",
736
+ "size_sanity",
737
+ ]
tasks/livewire__livewire-10628/environment/Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.
2
+ # Agent-agnostic: the agent (claude-code / openhands / codex / etc.)
3
+ # installs itself at run time via its harbor adapter. We only ship
4
+ # the source repo — the oracle + verifier arrive at verify time via
5
+ # tests/, never baked into the agent's image.
6
+ FROM python:3.12-slim
7
+ ARG GITHUB_TOKEN=
8
+ RUN apt-get update \
9
+ && apt-get install -y --no-install-recommends git ca-certificates curl \
10
+ && rm -rf /var/lib/apt/lists/*
11
+ RUN git config --global --add safe.directory /workspace \
12
+ && git config --global init.defaultBranch main \
13
+ && git config --global advice.detachedHead false
14
+ RUN if [ -n "$GITHUB_TOKEN" ]; then \
15
+ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin 5eb0926a9c9bec02e44d02962991aa4e3e0ac2bb 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard 5eb0926a9c9bec02e44d02962991aa4e3e0ac2bb \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base 5eb0926a9c9bec02e44d02962991aa4e3e0ac2bb \
26
+ && git remote remove origin 2>/dev/null || true
27
+ RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \
28
+ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \
29
+ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \
30
+ && git reflog expire --expire=now --all 2>/dev/null || true \
31
+ && git gc --prune=now 2>/dev/null || true
32
+ RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \
33
+ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \
34
+ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \
35
+ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \
36
+ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \
37
+ fi
tasks/livewire__livewire-10628/instruction.md ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** [4.x] Fix #[Session] non-primitives under JSON sessions
4
+
5
+ ## Description
6
+
7
+ ## Decision brief
8
+
9
+ Fresh Laravel applications now default to JSON session serialization (). That makes `#[Session]` fail for typed non-primitive properties: a `Collection` survives Livewire updates through the snapshot synth pipeline, but after a full page refresh Laravel reads the JSON session value as a plain array and PHP rejects assigning it to `?Collection`.
10
+
11
+ ```text
12
+ Cannot assign array to property ...::$list of type ?Illuminate\Support\Collection
13
+ ```
14
+
15
+ . Supersedes #10386.
16
+
17
+ ### Demand and product call
18
+
19
+ - Confirmed demand is one reporter and one explicit beneficiary, with no duplicate reports or independent “me too” comments found.
20
+ - The affected surface is broader than that count: Laravel's new default exposes every new app that combines `#[Session]` with Collection, Carbon, enum, model, nested, or custom synthesized values.
21
+ - This should be fixed in core rather than documented away. The complete userland escape hatch is switching session serialization back to `php`, but that undoes Laravel's security-motivated default. Array-backed state is a safe narrow workaround, not a satisfactory `#[Session]` contract.
22
+
23
+ ### Prior decisions
24
+
25
+ - #10252 was the original fix from @joshhanley. Review identified three constraints: don't create a careless hydration pathway, don't leak `HandleComponents` internals, and don't add cost or behavior changes to PHP-serialized sessions.
26
+ - #10276 extracted and secured `HandleSynths` specifically so features like `#[Session]` can reuse the registered synth pipeline without reaching into `HandleComponents`.
27
+ - #10630 added the missing storage-facing abstraction over `HandleSynths`: an authenticated, versioned `PersistedValueCodec`. It is now merged, and this PR builds directly on that core abstraction.
28
+ - #10386 applied that mechanism, but stored bare synth tuples. Any pre-existing session array shaped like `[data, ['s' => ...]]` could therefore be mistaken for Livewire metadata.
29
+ - Laravel solved its analogous JSON-session `ViewErrorBag` type loss with a narrowly owned codec in . This PR follows the same boundary while reusing Livewire's general synth registry.
30
+
31
+ ## Solution
32
+
33
+ Under `session.serialization=json`, `BaseSession` delegates its value to the `PersistedValueCodec` introduced in #10630. The codec decides whether synthesis is necessary and owns recursive traversal, component context, the strict versioned envelope, authentication, and synth security checks.
34
+
35
+ `BaseSession` now knows only that JSON sessions require storage encoding. It no longer understands synth tuples or calls `hydrate()` directly. Reads are decoded regardless of the current serializer so configuration changes do not strand encoded state; corrupt or stale values are forgotten and the property's default is preserved.
36
+
37
+ Consequences:
38
+
39
+ - Collections, Carbon, nested synthesized values, and registered custom synths round-trip through JSON sessions.
40
+ - JSON primitives remain raw.
41
+ - PHP-serialized sessions remain raw and pay no synth cost.
42
+ - Legacy tuple-shaped arrays remain ordinary arrays.
43
+ - Every encoded envelope is signed with the application key and scoped to its resolved session key.
44
+ - Client-authored, tampered, unsupported-version, and wrong-scope envelopes are rejected before synth hydration.
45
+ - Components intentionally using the same explicit session key can continue to share values.
46
+ - Authentic values for removed synthesizers are discarded safely instead of permanently failing every request.
47
+ - Class metadata still passes through `SecurityPolicy::validateClass()` before any synth can instantiate it.
48
+ - No `unserialize()` path is introduced.
49
+ - Forging a decodable persisted value requires `APP_KEY`, the same trust failure that permits forging Livewire snapshot checksums.
50
+
51
+ ## Progressive implementation
52
+
53
+ Each commit is a usable stage rather than a disconnected piece:
54
+
55
+ The prerequisite first makes the change easy in . This PR then builds the user-facing fix in usable stages:
56
+
57
+ 1. 🛹 — `BaseSession` delegates to the authenticated codec and solves the reporter's exact typed-Collection refresh failure.
58
+ 2. 🛴 — proves the same path for Carbon and nested synthesized values.
59
+ 3. 🚲 — proves raw PHP/primitives, explicit-key sharing, legacy tuple safety, stale-state recovery, and rejection of client-authored model envelopes under both serializers.
60
+ 4. 🚗 — preserves JSON-native arrays, proves registered custom synths and Eloquent models, asserts JSON mode, and exercises add → full refresh → add.
61
+
62
+ ## Reproduction and verification
63
+
64
+ Confirmed before the fix on the reporter's exact Livewire `v4.2.4` (`7d0bfa46`):
65
+
66
+ 1. Load the component successfully.
67
+ 2. Click **Add**; `1` renders.
68
+ 3. Refresh the page; Laravel returns HTTP 500 with the typed-property error above.
69
+
70
+ Confirmed after the fix in the same Laravel 13 playground:
71
+
72
+ 1. Click **Add**; `1` renders.
73
+ 2. Refresh; `1` is restored with no error.
74
+ 3. Click **Add** again; `1, 2` renders.
75
+
76
+ Automated verification:
77
+
78
+ - Persisted-value codec: 12 tests, 19 assertions.
79
+ - SupportSession feature suite: 16 tests, 20 assertions.
80
+ - Full unit suite: 1,504 tests, 4,251 assertions; 13 existing skips and 3 existing incomplete tests.
81
+ - Focused browser regression: 1 test, 5 assertions.
82
+ - Real Laravel 13 playground: `1` after update → `1` after full refresh → `1, 2` after the next update.
83
+ - Independent review reproduced an unsigned-envelope `ModelSynth` exploit against the first design; the final signed design directly tests and rejects that path under JSON and PHP sessions.
84
+
85
+ Session-backed Eloquent values retain normal `ModelSynth` lazy-loading semantics; this PR does not force model queries during `BaseSession::mount()`.
86
+
87
+ ## Immediate userland workaround
88
+
89
+ Apps unable to upgrade can keep JSON-native data in the session and derive a Collection:
90
+
91
+ ```php
92
+ #[Session]
93
+ public array $listData = [];
94
+
95
+ #[Computed]
96
+ public function list(): Collection
97
+ {
98
+ return collect($this->listData);
99
+ }
100
+ ```
101
+
102
+ This works for JSON-safe items but does not preserve arbitrary nested object types.
103
+
104
+ Implementation credit: this is rebuilt from @joshhanley's original work in #10252; Josh is credited as a co-author in the first commit.
105
+
106
+ ## Task
107
+
108
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5eb0926a9c9b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/livewire__livewire-10628/solution/patch.diff ADDED
@@ -0,0 +1,608 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/src/Features/SupportSession/BaseSession.php b/src/Features/SupportSession/BaseSession.php
2
+ index 0cd16c5a..774fc5cb 100644
3
+ --- a/src/Features/SupportSession/BaseSession.php
4
+ +++ b/src/Features/SupportSession/BaseSession.php
5
+ @@ -3,12 +3,16 @@
6
+ namespace Livewire\Features\SupportSession;
7
+
8
+ use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute;
9
+ +use Livewire\Mechanisms\HandleSynths\CorruptPersistedValueException;
10
+ +use Livewire\Mechanisms\HandleSynths\PersistedValueCodec;
11
+ use Illuminate\Support\Facades\Session;
12
+ use Attribute;
13
+
14
+ #[Attribute(Attribute::TARGET_PROPERTY)]
15
+ class BaseSession extends LivewireAttribute
16
+ {
17
+ + protected $codec;
18
+ +
19
+ function __construct(
20
+ protected $key = null,
21
+ ) {}
22
+ @@ -17,9 +21,23 @@ class BaseSession extends LivewireAttribute
23
+ {
24
+ if (! $this->exists()) return;
25
+
26
+ - $fromSession = $this->read();
27
+ + try {
28
+ + $fromSession = $this->read();
29
+ + } catch (CorruptPersistedValueException) {
30
+ + Session::forget($this->key());
31
+ +
32
+ + return;
33
+ + }
34
+
35
+ - $this->setValue($fromSession);
36
+ + // A stored value can become unassignable after it was persisted: its
37
+ + // type no longer matches the property (\TypeError), or it's a scalar
38
+ + // backing a since-removed enum case (\ValueError from Enum::from()).
39
+ + // Either way the stale value is forgotten and the default preserved.
40
+ + try {
41
+ + $this->setValue($fromSession);
42
+ + } catch (\TypeError|\ValueError) {
43
+ + Session::forget($this->key());
44
+ + }
45
+ }
46
+
47
+ public function dehydrate($context)
48
+ @@ -34,12 +52,43 @@ class BaseSession extends LivewireAttribute
49
+
50
+ protected function read()
51
+ {
52
+ - return Session::get($this->key());
53
+ + // Always decode so changing session serializers doesn't strand values
54
+ + // that Livewire encoded before the configuration changed.
55
+ + $key = $this->key();
56
+ +
57
+ + return $this->codec()->decodeFromStorage(
58
+ + Session::get($key),
59
+ + $this->component,
60
+ + $this->getName(),
61
+ + $key,
62
+ + );
63
+ }
64
+
65
+ protected function write()
66
+ {
67
+ - Session::put($this->key(), $this->getValue());
68
+ + $value = $this->getValue();
69
+ + $key = $this->key();
70
+ +
71
+ + if ($this->sessionIsJsonSerialized()) {
72
+ + $value = $this->codec()->encodeForStorage(
73
+ + $value,
74
+ + $this->component,
75
+ + $this->getName(),
76
+ + $key,
77
+ + );
78
+ + }
79
+ +
80
+ + Session::put($key, $value);
81
+ + }
82
+ +
83
+ + protected function sessionIsJsonSerialized()
84
+ + {
85
+ + return config('session.serialization', 'php') === 'json';
86
+ + }
87
+ +
88
+ + protected function codec()
89
+ + {
90
+ + return $this->codec ??= app(PersistedValueCodec::class);
91
+ }
92
+
93
+ protected function key()
94
+ diff --git a/src/Features/SupportSession/JsonSerializationBrowserTest.php b/src/Features/SupportSession/JsonSerializationBrowserTest.php
95
+ new file mode 100644
96
+ index 00000000..64bdb9bf
97
+ --- /dev/null
98
+ +++ b/src/Features/SupportSession/JsonSerializationBrowserTest.php
99
+ @@ -0,0 +1,56 @@
100
+ +<?php
101
+ +
102
+ +namespace Livewire\Features\SupportSession;
103
+ +
104
+ +use Illuminate\Support\Collection;
105
+ +use Livewire\Attributes\Session;
106
+ +use Livewire\Component;
107
+ +use Livewire\Livewire;
108
+ +use Tests\BrowserTestCase;
109
+ +
110
+ +class JsonSerializationBrowserTest extends BrowserTestCase
111
+ +{
112
+ + public static function tweakApplicationHook()
113
+ + {
114
+ + return function () {
115
+ + config(['session.serialization' => 'json']);
116
+ + };
117
+ + }
118
+ +
119
+ + public function test_collection_properties_survive_a_full_page_refresh()
120
+ + {
121
+ + Livewire::visit(new class extends Component {
122
+ + #[Session]
123
+ + public ?Collection $list = null;
124
+ +
125
+ + public function mount(): void
126
+ + {
127
+ + $this->list ??= collect();
128
+ + }
129
+ +
130
+ + public function add(): void
131
+ + {
132
+ + $this->list->push($this->list->count() + 1);
133
+ + }
134
+ +
135
+ + public function render()
136
+ + {
137
+ + return <<<'HTML'
138
+ + <div>
139
+ + <span dusk="serialization">{{ config('session.serialization') }}</span>
140
+ + <button dusk="button" wire:click="add">Add</button>
141
+ + <span dusk="list">{{ $list->implode(', ') }}</span>
142
+ + </div>
143
+ + HTML;
144
+ + }
145
+ + })
146
+ + ->assertSeeIn('@serialization', 'json')
147
+ + ->assertSeeIn('@list', '')
148
+ + ->waitForLivewire()->click('@button')
149
+ + ->assertSeeIn('@list', '1')
150
+ + ->refresh()
151
+ + ->assertSeeIn('@list', '1')
152
+ + ->waitForLivewire()->click('@button')
153
+ + ->assertSeeIn('@list', '1, 2');
154
+ + }
155
+ +}
156
+ diff --git a/src/Features/SupportSession/UnitTest.php b/src/Features/SupportSession/UnitTest.php
157
+ index 243f6895..e027d058 100644
158
+ --- a/src/Features/SupportSession/UnitTest.php
159
+ +++ b/src/Features/SupportSession/UnitTest.php
160
+ @@ -2,11 +2,19 @@
161
+
162
+ namespace Livewire\Features\SupportSession;
163
+
164
+ +use Illuminate\Database\Eloquent\Model;
165
+ +use Illuminate\Support\Carbon;
166
+ +use Illuminate\Support\Collection;
167
+ use Illuminate\Support\Facades\Session as FacadesSession;
168
+ use Livewire\Attributes\Session;
169
+ +use Livewire\Component;
170
+ +use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth;
171
+ +use Livewire\Mechanisms\HandleSynths\HandleSynths;
172
+ +use Livewire\Mechanisms\HandleSynths\PersistedValueCodec;
173
+ use Tests\TestCase;
174
+ use Livewire\Livewire;
175
+ use Tests\TestComponent;
176
+ +use Sushi\Sushi;
177
+
178
+ class UnitTest extends TestCase
179
+ {
180
+ @@ -43,4 +51,428 @@ class UnitTest extends TestCase
181
+
182
+ $this->assertTrue(FacadesSession::has('baz.2'));
183
+ }
184
+ +
185
+ + public function test_collection_properties_survive_json_session_serialization()
186
+ + {
187
+ + config(['session.serialization' => 'json']);
188
+ +
189
+ + app('session')->forgetDrivers();
190
+ +
191
+ + Livewire::test(ComponentWithSessionCollection::class)
192
+ + ->call('add');
193
+ +
194
+ + session()->save();
195
+ + session()->start();
196
+ +
197
+ + Livewire::test(ComponentWithSessionCollection::class)
198
+ + ->assertSet('list', fn ($list) => $list instanceof Collection && $list->all() === [1]);
199
+ + }
200
+ +
201
+ + public function test_synthesized_properties_survive_json_session_serialization()
202
+ + {
203
+ + config(['session.serialization' => 'json']);
204
+ +
205
+ + app('session')->forgetDrivers();
206
+ +
207
+ + $date = Carbon::parse('2026-01-15 10:00:00');
208
+ +
209
+ + Livewire::test(ComponentWithSynthesizedSessionProperties::class)
210
+ + ->set('when', $date)
211
+ + ->set('nested', ['list' => collect([1, 2]), 'when' => $date]);
212
+ +
213
+ + session()->save();
214
+ + session()->start();
215
+ +
216
+ + Livewire::test(ComponentWithSynthesizedSessionProperties::class)
217
+ + ->assertSet('when', fn ($when) => $when instanceof Carbon && $when->equalTo($date))
218
+ + ->assertSet('nested', fn ($nested) => $nested['list'] instanceof Collection
219
+ + && $nested['list']->all() === [1, 2]
220
+ + && $nested['when'] instanceof Carbon
221
+ + && $nested['when']->equalTo($date));
222
+ + }
223
+ +
224
+ + public function test_custom_synthesized_properties_survive_json_session_serialization()
225
+ + {
226
+ + config(['session.serialization' => 'json']);
227
+ +
228
+ + app('session')->forgetDrivers();
229
+ + app(HandleSynths::class)->registerSynth(CustomSessionValueSynth::class);
230
+ +
231
+ + Livewire::test(ComponentWithCustomSynthesizedSessionProperty::class);
232
+ +
233
+ + session()->save();
234
+ + session()->start();
235
+ +
236
+ + Livewire::test(ComponentWithCustomSynthesizedSessionProperty::class)
237
+ + ->assertSet('value', fn ($value) => $value instanceof CustomSessionValue && $value->value === 'persisted');
238
+ + }
239
+ +
240
+ + public function test_model_properties_survive_json_session_serialization()
241
+ + {
242
+ + config(['session.serialization' => 'json']);
243
+ +
244
+ + app('session')->forgetDrivers();
245
+ +
246
+ + Livewire::test(ComponentWithSessionModel::class)
247
+ + ->assertSet('article', fn ($article) => $article instanceof SessionArticle && $article->title === 'First');
248
+ +
249
+ + session()->save();
250
+ + session()->start();
251
+ +
252
+ + Livewire::test(ComponentWithSessionModel::class)
253
+ + ->assertSet('article', fn ($article) => $article instanceof SessionArticle && $article->title === 'First');
254
+ + }
255
+ +
256
+ + public function test_php_sessions_continue_to_store_values_raw()
257
+ + {
258
+ + config(['session.serialization' => 'php']);
259
+ +
260
+ + app('session')->forgetDrivers();
261
+ +
262
+ + Livewire::test(ComponentWithSessionCollection::class)
263
+ + ->call('add');
264
+ +
265
+ + $stored = session('collection');
266
+ +
267
+ + $this->assertInstanceOf(Collection::class, $stored);
268
+ + $this->assertSame([1], $stored->all());
269
+ + }
270
+ +
271
+ + public function test_json_sessions_continue_to_store_primitive_values_raw()
272
+ + {
273
+ + config(['session.serialization' => 'json']);
274
+ +
275
+ + app('session')->forgetDrivers();
276
+ +
277
+ + Livewire::test(ComponentWithPrimitiveSessionProperty::class)
278
+ + ->set('count', 1);
279
+ +
280
+ + $this->assertSame(1, session('primitive'));
281
+ + $this->assertSame(['search' => '', 'tags' => [1, 2]], session('json-native'));
282
+ + }
283
+ +
284
+ + public function test_legacy_tuple_shaped_arrays_are_not_treated_as_synthetic_values()
285
+ + {
286
+ + $tuple = [['one', 'two'], ['s' => 'clctn', 'class' => Collection::class]];
287
+ +
288
+ + FacadesSession::put('legacy-tuple', $tuple);
289
+ +
290
+ + Livewire::test(ComponentWithRawSessionArray::class)
291
+ + ->assertSet('value', $tuple);
292
+ + }
293
+ +
294
+ + public function test_session_envelopes_are_decoded_even_after_switching_to_php_serialization()
295
+ + {
296
+ + config(['session.serialization' => 'json']);
297
+ +
298
+ + app('session')->forgetDrivers();
299
+ +
300
+ + Livewire::test(ComponentWithSessionCollection::class)
301
+ + ->call('add');
302
+ +
303
+ + config(['session.serialization' => 'php']);
304
+ +
305
+ + Livewire::test(ComponentWithSessionCollection::class)
306
+ + ->assertSet('list', fn ($list) => $list instanceof Collection && $list->all() === [1]);
307
+ + }
308
+ +
309
+ + public function test_client_authored_synth_envelopes_are_discarded_in_json_sessions()
310
+ + {
311
+ + $this->assertClientAuthoredSynthEnvelopeIsDiscarded('json');
312
+ + }
313
+ +
314
+ + public function test_client_authored_synth_envelopes_are_discarded_in_php_sessions()
315
+ + {
316
+ + $this->assertClientAuthoredSynthEnvelopeIsDiscarded('php');
317
+ + }
318
+ +
319
+ + public function test_unreadable_persisted_envelopes_are_discarded()
320
+ + {
321
+ + config(['session.serialization' => 'json']);
322
+ +
323
+ + app('session')->forgetDrivers();
324
+ +
325
+ + Livewire::test(ComponentWithSessionCollection::class)
326
+ + ->call('add');
327
+ +
328
+ + $stored = session('collection');
329
+ + $stored[PersistedValueCodec::KEY]['version']++;
330
+ +
331
+ + FacadesSession::put('collection', $stored);
332
+ +
333
+ + Livewire::test(ComponentWithSessionCollection::class)
334
+ + ->assertSet('list', fn ($list) => $list instanceof Collection && $list->isEmpty());
335
+ + }
336
+ +
337
+ + public function test_components_can_share_an_explicit_session_key()
338
+ + {
339
+ + config(['session.serialization' => 'json']);
340
+ +
341
+ + app('session')->forgetDrivers();
342
+ +
343
+ + Livewire::test(ComponentWithSessionCollection::class)
344
+ + ->call('add');
345
+ +
346
+ + session()->save();
347
+ + session()->start();
348
+ +
349
+ + Livewire::test(ComponentReadingSharedSessionCollection::class)
350
+ + ->assertSet('items', fn ($items) => $items instanceof Collection && $items->all() === [1]);
351
+ + }
352
+ +
353
+ + public function test_values_for_synths_that_are_no_longer_registered_are_discarded()
354
+ + {
355
+ + config(['session.serialization' => 'json']);
356
+ +
357
+ + app('session')->forgetDrivers();
358
+ +
359
+ + $encoded = app(PersistedValueCodec::class)->encodeForStorage(
360
+ + new \Illuminate\Foundation\Auth\User,
361
+ + new TestComponent,
362
+ + 'value',
363
+ + 'dangerous-value',
364
+ + );
365
+ +
366
+ + FacadesSession::put('dangerous-value', $encoded);
367
+ +
368
+ + app()->instance(
369
+ + \Livewire\Mechanisms\HandleSynths\HandleSynths::class,
370
+ + new \Livewire\Mechanisms\HandleSynths\HandleSynths,
371
+ + );
372
+ +
373
+ + Livewire::test(ComponentWithDangerousSessionProperty::class)
374
+ + ->assertSet('value', 'safe');
375
+ + }
376
+ +
377
+ + public function test_json_arrays_left_by_older_versions_are_discarded_from_typed_properties()
378
+ + {
379
+ + config(['session.serialization' => 'json']);
380
+ +
381
+ + app('session')->forgetDrivers();
382
+ + FacadesSession::put('stale-collection', [1, 2]);
383
+ +
384
+ + Livewire::test(ComponentWithStaleSessionCollection::class)
385
+ + ->assertSet('list', null);
386
+ + }
387
+ +
388
+ + public function test_stale_enum_backing_values_are_discarded_from_typed_properties()
389
+ + {
390
+ + config(['session.serialization' => 'json']);
391
+ +
392
+ + app('session')->forgetDrivers();
393
+ +
394
+ + // A scalar backing an enum case that no longer exists (a removed or
395
+ + // renamed case, or a value written before the enum changed). Coercing
396
+ + // it throws a ValueError that must be recovered from, not surfaced.
397
+ + FacadesSession::put('stale-enum', 'archived');
398
+ +
399
+ + Livewire::test(ComponentWithSessionEnum::class)
400
+ + ->assertSet('status', null);
401
+ + }
402
+ +
403
+ + protected function assertClientAuthoredSynthEnvelopeIsDiscarded($serialization)
404
+ + {
405
+ + config(['session.serialization' => $serialization]);
406
+ +
407
+ + app('session')->forgetDrivers();
408
+ +
409
+ + Livewire::test(ComponentWithDangerousSessionProperty::class)
410
+ + ->set('value', [
411
+ + PersistedValueCodec::KEY => [
412
+ + 'version' => PersistedValueCodec::VERSION,
413
+ + 'value' => [null, [
414
+ + 's' => 'mdl',
415
+ + 'class' => \Illuminate\Foundation\Auth\User::class,
416
+ + 'key' => 1,
417
+ + ]],
418
+ + ],
419
+ + ]);
420
+ +
421
+ + session()->save();
422
+ + session()->start();
423
+ +
424
+ + Livewire::test(ComponentWithDangerousSessionProperty::class)
425
+ + ->assertSet('value', 'safe');
426
+ + }
427
+ +}
428
+ +
429
+ +class ComponentWithSessionCollection extends Component
430
+ +{
431
+ + #[Session(key: 'collection')]
432
+ + public ?Collection $list = null;
433
+ +
434
+ + public function mount(): void
435
+ + {
436
+ + $this->list ??= collect();
437
+ + }
438
+ +
439
+ + public function add(): void
440
+ + {
441
+ + $this->list->push($this->list->count() + 1);
442
+ + }
443
+ +
444
+ + public function render()
445
+ + {
446
+ + return '<div>{{ $list->implode(", ") }}</div>';
447
+ + }
448
+ +}
449
+ +
450
+ +class ComponentReadingSharedSessionCollection extends Component
451
+ +{
452
+ + #[Session(key: 'collection')]
453
+ + public ?Collection $items = null;
454
+ +
455
+ + public function mount(): void
456
+ + {
457
+ + $this->items ??= collect();
458
+ + }
459
+ +
460
+ + public function render()
461
+ + {
462
+ + return '<div></div>';
463
+ + }
464
+ +}
465
+ +
466
+ +class ComponentWithSynthesizedSessionProperties extends Component
467
+ +{
468
+ + #[Session]
469
+ + public ?Carbon $when = null;
470
+ +
471
+ + #[Session]
472
+ + public array $nested = [];
473
+ +
474
+ + public function render()
475
+ + {
476
+ + return '<div></div>';
477
+ + }
478
+ +}
479
+ +
480
+ +class ComponentWithCustomSynthesizedSessionProperty extends Component
481
+ +{
482
+ + #[Session]
483
+ + public ?CustomSessionValue $value = null;
484
+ +
485
+ + public function mount()
486
+ + {
487
+ + $this->value ??= new CustomSessionValue('persisted');
488
+ + }
489
+ +
490
+ + public function render()
491
+ + {
492
+ + return '<div></div>';
493
+ + }
494
+ +}
495
+ +
496
+ +class ComponentWithSessionModel extends Component
497
+ +{
498
+ + #[Session(key: 'article')]
499
+ + public ?SessionArticle $article = null;
500
+ +
501
+ + public function mount()
502
+ + {
503
+ + $this->article ??= SessionArticle::first();
504
+ + }
505
+ +
506
+ + public function render()
507
+ + {
508
+ + return '<div></div>';
509
+ + }
510
+ +}
511
+ +
512
+ +class SessionArticle extends Model
513
+ +{
514
+ + use Sushi;
515
+ +
516
+ + protected $rows = [
517
+ + ['title' => 'First'],
518
+ + ];
519
+ +}
520
+ +
521
+ +class CustomSessionValue
522
+ +{
523
+ + public function __construct(public string $value) {}
524
+ +}
525
+ +
526
+ +class CustomSessionValueSynth extends Synth
527
+ +{
528
+ + public static $key = 'session-value';
529
+ +
530
+ + public static function match($target)
531
+ + {
532
+ + return $target instanceof CustomSessionValue;
533
+ + }
534
+ +
535
+ + public function dehydrate($target)
536
+ + {
537
+ + return [$target->value, []];
538
+ + }
539
+ +
540
+ + public function hydrate($value)
541
+ + {
542
+ + return new CustomSessionValue($value);
543
+ + }
544
+ +}
545
+ +
546
+ +class ComponentWithPrimitiveSessionProperty extends Component
547
+ +{
548
+ + #[Session(key: 'primitive')]
549
+ + public int $count = 0;
550
+ +
551
+ + #[Session(key: 'json-native')]
552
+ + public array $filters = ['search' => '', 'tags' => [1, 2]];
553
+ +
554
+ + public function render()
555
+ + {
556
+ + return '<div></div>';
557
+ + }
558
+ +}
559
+ +
560
+ +class ComponentWithRawSessionArray extends Component
561
+ +{
562
+ + #[Session(key: 'legacy-tuple')]
563
+ + public array $value = [];
564
+ +
565
+ + public function render()
566
+ + {
567
+ + return '<div></div>';
568
+ + }
569
+ +}
570
+ +
571
+ +class ComponentWithDangerousSessionProperty extends Component
572
+ +{
573
+ + #[Session(key: 'dangerous-value')]
574
+ + public $value = 'safe';
575
+ +
576
+ + public function render()
577
+ + {
578
+ + return '<div></div>';
579
+ + }
580
+ +}
581
+ +
582
+ +class ComponentWithStaleSessionCollection extends Component
583
+ +{
584
+ + #[Session(key: 'stale-collection')]
585
+ + public ?Collection $list = null;
586
+ +
587
+ + public function render()
588
+ + {
589
+ + return '<div></div>';
590
+ + }
591
+ +}
592
+ +
593
+ +enum SessionStatus: string
594
+ +{
595
+ + case Draft = 'draft';
596
+ + case Published = 'published';
597
+ +}
598
+ +
599
+ +class ComponentWithSessionEnum extends Component
600
+ +{
601
+ + #[Session(key: 'stale-enum')]
602
+ + public ?SessionStatus $status = null;
603
+ +
604
+ + public function render()
605
+ + {
606
+ + return '<div></div>';
607
+ + }
608
+ }
tasks/livewire__livewire-10628/solution/solve.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euxo pipefail
3
+ cd /workspace
4
+ git config --global --add safe.directory /workspace
5
+ PATCH="$(dirname "$0")/patch.diff"
6
+ git apply --verbose --reject "$PATCH"
tasks/livewire__livewire-10628/task.toml ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/livewire__livewire-10628"
5
+ description = "[4.x] Fix #[Session] non-primitives under JSON sessions"
6
+
7
+ [metadata]
8
+ difficulty = "large"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "livewire",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "livewire/livewire"
19
+ ref = "5eb0926a9c9bec02e44d02962991aa4e3e0ac2bb"
20
+ reference = "https://github.com/livewire/livewire/pull/10628"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:51.536200+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:65324105677c0ba95133b1d031c3dd9f56e2dec59f97acbba0e5d6d839049390"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-08-30T12:22:19Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "src/Features/SupportSession/BaseSession.php",
34
+ "src/Features/SupportSession/JsonSerializationBrowserTest.php",
35
+ "src/Features/SupportSession/UnitTest.php",
36
+ ]
37
+ bootstrap_image = "python:3.12-slim"
38
+
39
+ [metadata.repo2env.reward_calibration]
40
+ baseline_reward = 0.0
41
+ loc_changed = 545
42
+ difficulty = "large"
43
+
44
+ [metadata.repo2env.evaluation]
45
+ schema_version = "1"
46
+ status = "unverified"
47
+ stage = "generation"
48
+ reason_codes = [
49
+ "validation_not_run",
50
+ ]
51
+ detail = "Generated task; validation has not been established."
52
+ provenance = "unknown"
53
+ evidence = []
54
+
55
+ [metadata.repo2env.reproducibility]
56
+ mode = "inline_dockerfile"
57
+ image_ref = "python:3.12-slim"
58
+ image_tag = "python:3.12-slim"
59
+ image_visibility = "public"
60
+ pushed_at = "2026-11-16T16:20:01.366870+00:00"
61
+ pushed_by = "scalingX"
62
+ inline_recipe_sha256 = "sha256:3f1e3ad1d08e8be0ccdd7b3949a3344a447196e075b10ed056a3c65f87c74f0b"
63
+ inline_recipe_lines = 37
64
+ inline_recipe_source = "user_dockerfile"
65
+
66
+ [agent]
67
+ timeout_sec = 1800.0
68
+
69
+ [verifier]
70
+ timeout_sec = 300.0
tasks/livewire__livewire-10628/tests/capture.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone PR-diff capture without executing workspace Git configuration.
2
+
3
+ The emitted task uses a regular clone with a pinned base commit. Only its
4
+ object store is read: refs, index, config, hooks and replacement refs are not
5
+ used. This is a configuration boundary, not a sandbox for a malicious process
6
+ that can modify the verifier, binaries or object store while capture runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+
22
+ def capture(workspace: Path, base_commit: str) -> bytes:
23
+ """Capture tracked and new files through a fresh private Git index."""
24
+ if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit):
25
+ raise ValueError("Expected the task's pinned SHA-1 base commit")
26
+ objects = workspace.resolve() / ".git" / "objects"
27
+ if not objects.is_dir():
28
+ raise ValueError("The task's cloned Git object store is missing")
29
+ git = shutil.which("git", path=os.defpath)
30
+ if git is None:
31
+ raise FileNotFoundError("System git is unavailable")
32
+ with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary:
33
+ private = Path(temporary)
34
+ # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs,
35
+ # system/global includes, user attributes, templates or credential env.
36
+ env = {
37
+ "PATH": os.defpath,
38
+ "HOME": temporary,
39
+ "XDG_CONFIG_HOME": temporary,
40
+ "GIT_CONFIG_NOSYSTEM": "1",
41
+ "GIT_CONFIG_GLOBAL": os.devnull,
42
+ "GIT_ATTR_NOSYSTEM": "1",
43
+ "GIT_NO_REPLACE_OBJECTS": "1",
44
+ "GIT_NO_LAZY_FETCH": "1",
45
+ "GIT_TERMINAL_PROMPT": "0",
46
+ "LC_ALL": "C",
47
+ }
48
+ subprocess.run(
49
+ [git, "init", "--quiet", "--template=", str(private / "repository")],
50
+ env=env,
51
+ cwd=private,
52
+ check=True,
53
+ capture_output=True,
54
+ timeout=60,
55
+ )
56
+ env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False)
57
+ command = [
58
+ git,
59
+ f"--git-dir={private / 'repository/.git'}",
60
+ f"--work-tree={workspace.resolve()}",
61
+ ]
62
+
63
+ def run(*args: str) -> bytes:
64
+ return subprocess.run(
65
+ [*command, *args],
66
+ env=env,
67
+ cwd=workspace,
68
+ check=True,
69
+ capture_output=True,
70
+ timeout=60,
71
+ ).stdout
72
+
73
+ run("read-tree", f"{base_commit}^{{tree}}")
74
+ # All filter drivers are undefined in the private configuration. The
75
+ # workspace's clean filters, fsmonitor and hooks cannot be invoked.
76
+ run("add", "--all", "--", ".")
77
+ return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
78
+
79
+
80
+ def main(argv: list[str] | None = None) -> int:
81
+ parser = argparse.ArgumentParser(description=__doc__)
82
+ parser.add_argument("workspace", type=Path)
83
+ parser.add_argument("base_commit")
84
+ args = parser.parse_args(argv)
85
+ try:
86
+ patch = capture(args.workspace, args.base_commit)
87
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
88
+ # Do not echo child stderr: it may contain workspace-controlled data.
89
+ sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n")
90
+ return 1
91
+ sys.stdout.buffer.write(patch)
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
tasks/livewire__livewire-10628/tests/instruction.md ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** [4.x] Fix #[Session] non-primitives under JSON sessions
4
+
5
+ ## Description
6
+
7
+ ## Decision brief
8
+
9
+ Fresh Laravel applications now default to JSON session serialization (). That makes `#[Session]` fail for typed non-primitive properties: a `Collection` survives Livewire updates through the snapshot synth pipeline, but after a full page refresh Laravel reads the JSON session value as a plain array and PHP rejects assigning it to `?Collection`.
10
+
11
+ ```text
12
+ Cannot assign array to property ...::$list of type ?Illuminate\Support\Collection
13
+ ```
14
+
15
+ . Supersedes #10386.
16
+
17
+ ### Demand and product call
18
+
19
+ - Confirmed demand is one reporter and one explicit beneficiary, with no duplicate reports or independent “me too” comments found.
20
+ - The affected surface is broader than that count: Laravel's new default exposes every new app that combines `#[Session]` with Collection, Carbon, enum, model, nested, or custom synthesized values.
21
+ - This should be fixed in core rather than documented away. The complete userland escape hatch is switching session serialization back to `php`, but that undoes Laravel's security-motivated default. Array-backed state is a safe narrow workaround, not a satisfactory `#[Session]` contract.
22
+
23
+ ### Prior decisions
24
+
25
+ - #10252 was the original fix from @joshhanley. Review identified three constraints: don't create a careless hydration pathway, don't leak `HandleComponents` internals, and don't add cost or behavior changes to PHP-serialized sessions.
26
+ - #10276 extracted and secured `HandleSynths` specifically so features like `#[Session]` can reuse the registered synth pipeline without reaching into `HandleComponents`.
27
+ - #10630 added the missing storage-facing abstraction over `HandleSynths`: an authenticated, versioned `PersistedValueCodec`. It is now merged, and this PR builds directly on that core abstraction.
28
+ - #10386 applied that mechanism, but stored bare synth tuples. Any pre-existing session array shaped like `[data, ['s' => ...]]` could therefore be mistaken for Livewire metadata.
29
+ - Laravel solved its analogous JSON-session `ViewErrorBag` type loss with a narrowly owned codec in . This PR follows the same boundary while reusing Livewire's general synth registry.
30
+
31
+ ## Solution
32
+
33
+ Under `session.serialization=json`, `BaseSession` delegates its value to the `PersistedValueCodec` introduced in #10630. The codec decides whether synthesis is necessary and owns recursive traversal, component context, the strict versioned envelope, authentication, and synth security checks.
34
+
35
+ `BaseSession` now knows only that JSON sessions require storage encoding. It no longer understands synth tuples or calls `hydrate()` directly. Reads are decoded regardless of the current serializer so configuration changes do not strand encoded state; corrupt or stale values are forgotten and the property's default is preserved.
36
+
37
+ Consequences:
38
+
39
+ - Collections, Carbon, nested synthesized values, and registered custom synths round-trip through JSON sessions.
40
+ - JSON primitives remain raw.
41
+ - PHP-serialized sessions remain raw and pay no synth cost.
42
+ - Legacy tuple-shaped arrays remain ordinary arrays.
43
+ - Every encoded envelope is signed with the application key and scoped to its resolved session key.
44
+ - Client-authored, tampered, unsupported-version, and wrong-scope envelopes are rejected before synth hydration.
45
+ - Components intentionally using the same explicit session key can continue to share values.
46
+ - Authentic values for removed synthesizers are discarded safely instead of permanently failing every request.
47
+ - Class metadata still passes through `SecurityPolicy::validateClass()` before any synth can instantiate it.
48
+ - No `unserialize()` path is introduced.
49
+ - Forging a decodable persisted value requires `APP_KEY`, the same trust failure that permits forging Livewire snapshot checksums.
50
+
51
+ ## Progressive implementation
52
+
53
+ Each commit is a usable stage rather than a disconnected piece:
54
+
55
+ The prerequisite first makes the change easy in . This PR then builds the user-facing fix in usable stages:
56
+
57
+ 1. 🛹 — `BaseSession` delegates to the authenticated codec and solves the reporter's exact typed-Collection refresh failure.
58
+ 2. 🛴 — proves the same path for Carbon and nested synthesized values.
59
+ 3. 🚲 — proves raw PHP/primitives, explicit-key sharing, legacy tuple safety, stale-state recovery, and rejection of client-authored model envelopes under both serializers.
60
+ 4. 🚗 — preserves JSON-native arrays, proves registered custom synths and Eloquent models, asserts JSON mode, and exercises add → full refresh → add.
61
+
62
+ ## Reproduction and verification
63
+
64
+ Confirmed before the fix on the reporter's exact Livewire `v4.2.4` (`7d0bfa46`):
65
+
66
+ 1. Load the component successfully.
67
+ 2. Click **Add**; `1` renders.
68
+ 3. Refresh the page; Laravel returns HTTP 500 with the typed-property error above.
69
+
70
+ Confirmed after the fix in the same Laravel 13 playground:
71
+
72
+ 1. Click **Add**; `1` renders.
73
+ 2. Refresh; `1` is restored with no error.
74
+ 3. Click **Add** again; `1, 2` renders.
75
+
76
+ Automated verification:
77
+
78
+ - Persisted-value codec: 12 tests, 19 assertions.
79
+ - SupportSession feature suite: 16 tests, 20 assertions.
80
+ - Full unit suite: 1,504 tests, 4,251 assertions; 13 existing skips and 3 existing incomplete tests.
81
+ - Focused browser regression: 1 test, 5 assertions.
82
+ - Real Laravel 13 playground: `1` after update → `1` after full refresh → `1, 2` after the next update.
83
+ - Independent review reproduced an unsigned-envelope `ModelSynth` exploit against the first design; the final signed design directly tests and rejects that path under JSON and PHP sessions.
84
+
85
+ Session-backed Eloquent values retain normal `ModelSynth` lazy-loading semantics; this PR does not force model queries during `BaseSession::mount()`.
86
+
87
+ ## Immediate userland workaround
88
+
89
+ Apps unable to upgrade can keep JSON-native data in the session and derive a Collection:
90
+
91
+ ```php
92
+ #[Session]
93
+ public array $listData = [];
94
+
95
+ #[Computed]
96
+ public function list(): Collection
97
+ {
98
+ return collect($this->listData);
99
+ }
100
+ ```
101
+
102
+ This works for JSON-safe items but does not preserve arbitrary nested object types.
103
+
104
+ Implementation credit: this is rebuilt from @joshhanley's original work in #10252; Josh is credited as a co-author in the first commit.
105
+
106
+ ## Task
107
+
108
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `5eb0926a9c9b`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/livewire__livewire-10628/tests/oracle.patch ADDED
@@ -0,0 +1,608 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/src/Features/SupportSession/BaseSession.php b/src/Features/SupportSession/BaseSession.php
2
+ index 0cd16c5a..774fc5cb 100644
3
+ --- a/src/Features/SupportSession/BaseSession.php
4
+ +++ b/src/Features/SupportSession/BaseSession.php
5
+ @@ -3,12 +3,16 @@
6
+ namespace Livewire\Features\SupportSession;
7
+
8
+ use Livewire\Features\SupportAttributes\Attribute as LivewireAttribute;
9
+ +use Livewire\Mechanisms\HandleSynths\CorruptPersistedValueException;
10
+ +use Livewire\Mechanisms\HandleSynths\PersistedValueCodec;
11
+ use Illuminate\Support\Facades\Session;
12
+ use Attribute;
13
+
14
+ #[Attribute(Attribute::TARGET_PROPERTY)]
15
+ class BaseSession extends LivewireAttribute
16
+ {
17
+ + protected $codec;
18
+ +
19
+ function __construct(
20
+ protected $key = null,
21
+ ) {}
22
+ @@ -17,9 +21,23 @@ class BaseSession extends LivewireAttribute
23
+ {
24
+ if (! $this->exists()) return;
25
+
26
+ - $fromSession = $this->read();
27
+ + try {
28
+ + $fromSession = $this->read();
29
+ + } catch (CorruptPersistedValueException) {
30
+ + Session::forget($this->key());
31
+ +
32
+ + return;
33
+ + }
34
+
35
+ - $this->setValue($fromSession);
36
+ + // A stored value can become unassignable after it was persisted: its
37
+ + // type no longer matches the property (\TypeError), or it's a scalar
38
+ + // backing a since-removed enum case (\ValueError from Enum::from()).
39
+ + // Either way the stale value is forgotten and the default preserved.
40
+ + try {
41
+ + $this->setValue($fromSession);
42
+ + } catch (\TypeError|\ValueError) {
43
+ + Session::forget($this->key());
44
+ + }
45
+ }
46
+
47
+ public function dehydrate($context)
48
+ @@ -34,12 +52,43 @@ class BaseSession extends LivewireAttribute
49
+
50
+ protected function read()
51
+ {
52
+ - return Session::get($this->key());
53
+ + // Always decode so changing session serializers doesn't strand values
54
+ + // that Livewire encoded before the configuration changed.
55
+ + $key = $this->key();
56
+ +
57
+ + return $this->codec()->decodeFromStorage(
58
+ + Session::get($key),
59
+ + $this->component,
60
+ + $this->getName(),
61
+ + $key,
62
+ + );
63
+ }
64
+
65
+ protected function write()
66
+ {
67
+ - Session::put($this->key(), $this->getValue());
68
+ + $value = $this->getValue();
69
+ + $key = $this->key();
70
+ +
71
+ + if ($this->sessionIsJsonSerialized()) {
72
+ + $value = $this->codec()->encodeForStorage(
73
+ + $value,
74
+ + $this->component,
75
+ + $this->getName(),
76
+ + $key,
77
+ + );
78
+ + }
79
+ +
80
+ + Session::put($key, $value);
81
+ + }
82
+ +
83
+ + protected function sessionIsJsonSerialized()
84
+ + {
85
+ + return config('session.serialization', 'php') === 'json';
86
+ + }
87
+ +
88
+ + protected function codec()
89
+ + {
90
+ + return $this->codec ??= app(PersistedValueCodec::class);
91
+ }
92
+
93
+ protected function key()
94
+ diff --git a/src/Features/SupportSession/JsonSerializationBrowserTest.php b/src/Features/SupportSession/JsonSerializationBrowserTest.php
95
+ new file mode 100644
96
+ index 00000000..64bdb9bf
97
+ --- /dev/null
98
+ +++ b/src/Features/SupportSession/JsonSerializationBrowserTest.php
99
+ @@ -0,0 +1,56 @@
100
+ +<?php
101
+ +
102
+ +namespace Livewire\Features\SupportSession;
103
+ +
104
+ +use Illuminate\Support\Collection;
105
+ +use Livewire\Attributes\Session;
106
+ +use Livewire\Component;
107
+ +use Livewire\Livewire;
108
+ +use Tests\BrowserTestCase;
109
+ +
110
+ +class JsonSerializationBrowserTest extends BrowserTestCase
111
+ +{
112
+ + public static function tweakApplicationHook()
113
+ + {
114
+ + return function () {
115
+ + config(['session.serialization' => 'json']);
116
+ + };
117
+ + }
118
+ +
119
+ + public function test_collection_properties_survive_a_full_page_refresh()
120
+ + {
121
+ + Livewire::visit(new class extends Component {
122
+ + #[Session]
123
+ + public ?Collection $list = null;
124
+ +
125
+ + public function mount(): void
126
+ + {
127
+ + $this->list ??= collect();
128
+ + }
129
+ +
130
+ + public function add(): void
131
+ + {
132
+ + $this->list->push($this->list->count() + 1);
133
+ + }
134
+ +
135
+ + public function render()
136
+ + {
137
+ + return <<<'HTML'
138
+ + <div>
139
+ + <span dusk="serialization">{{ config('session.serialization') }}</span>
140
+ + <button dusk="button" wire:click="add">Add</button>
141
+ + <span dusk="list">{{ $list->implode(', ') }}</span>
142
+ + </div>
143
+ + HTML;
144
+ + }
145
+ + })
146
+ + ->assertSeeIn('@serialization', 'json')
147
+ + ->assertSeeIn('@list', '')
148
+ + ->waitForLivewire()->click('@button')
149
+ + ->assertSeeIn('@list', '1')
150
+ + ->refresh()
151
+ + ->assertSeeIn('@list', '1')
152
+ + ->waitForLivewire()->click('@button')
153
+ + ->assertSeeIn('@list', '1, 2');
154
+ + }
155
+ +}
156
+ diff --git a/src/Features/SupportSession/UnitTest.php b/src/Features/SupportSession/UnitTest.php
157
+ index 243f6895..e027d058 100644
158
+ --- a/src/Features/SupportSession/UnitTest.php
159
+ +++ b/src/Features/SupportSession/UnitTest.php
160
+ @@ -2,11 +2,19 @@
161
+
162
+ namespace Livewire\Features\SupportSession;
163
+
164
+ +use Illuminate\Database\Eloquent\Model;
165
+ +use Illuminate\Support\Carbon;
166
+ +use Illuminate\Support\Collection;
167
+ use Illuminate\Support\Facades\Session as FacadesSession;
168
+ use Livewire\Attributes\Session;
169
+ +use Livewire\Component;
170
+ +use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth;
171
+ +use Livewire\Mechanisms\HandleSynths\HandleSynths;
172
+ +use Livewire\Mechanisms\HandleSynths\PersistedValueCodec;
173
+ use Tests\TestCase;
174
+ use Livewire\Livewire;
175
+ use Tests\TestComponent;
176
+ +use Sushi\Sushi;
177
+
178
+ class UnitTest extends TestCase
179
+ {
180
+ @@ -43,4 +51,428 @@ class UnitTest extends TestCase
181
+
182
+ $this->assertTrue(FacadesSession::has('baz.2'));
183
+ }
184
+ +
185
+ + public function test_collection_properties_survive_json_session_serialization()
186
+ + {
187
+ + config(['session.serialization' => 'json']);
188
+ +
189
+ + app('session')->forgetDrivers();
190
+ +
191
+ + Livewire::test(ComponentWithSessionCollection::class)
192
+ + ->call('add');
193
+ +
194
+ + session()->save();
195
+ + session()->start();
196
+ +
197
+ + Livewire::test(ComponentWithSessionCollection::class)
198
+ + ->assertSet('list', fn ($list) => $list instanceof Collection && $list->all() === [1]);
199
+ + }
200
+ +
201
+ + public function test_synthesized_properties_survive_json_session_serialization()
202
+ + {
203
+ + config(['session.serialization' => 'json']);
204
+ +
205
+ + app('session')->forgetDrivers();
206
+ +
207
+ + $date = Carbon::parse('2026-01-15 10:00:00');
208
+ +
209
+ + Livewire::test(ComponentWithSynthesizedSessionProperties::class)
210
+ + ->set('when', $date)
211
+ + ->set('nested', ['list' => collect([1, 2]), 'when' => $date]);
212
+ +
213
+ + session()->save();
214
+ + session()->start();
215
+ +
216
+ + Livewire::test(ComponentWithSynthesizedSessionProperties::class)
217
+ + ->assertSet('when', fn ($when) => $when instanceof Carbon && $when->equalTo($date))
218
+ + ->assertSet('nested', fn ($nested) => $nested['list'] instanceof Collection
219
+ + && $nested['list']->all() === [1, 2]
220
+ + && $nested['when'] instanceof Carbon
221
+ + && $nested['when']->equalTo($date));
222
+ + }
223
+ +
224
+ + public function test_custom_synthesized_properties_survive_json_session_serialization()
225
+ + {
226
+ + config(['session.serialization' => 'json']);
227
+ +
228
+ + app('session')->forgetDrivers();
229
+ + app(HandleSynths::class)->registerSynth(CustomSessionValueSynth::class);
230
+ +
231
+ + Livewire::test(ComponentWithCustomSynthesizedSessionProperty::class);
232
+ +
233
+ + session()->save();
234
+ + session()->start();
235
+ +
236
+ + Livewire::test(ComponentWithCustomSynthesizedSessionProperty::class)
237
+ + ->assertSet('value', fn ($value) => $value instanceof CustomSessionValue && $value->value === 'persisted');
238
+ + }
239
+ +
240
+ + public function test_model_properties_survive_json_session_serialization()
241
+ + {
242
+ + config(['session.serialization' => 'json']);
243
+ +
244
+ + app('session')->forgetDrivers();
245
+ +
246
+ + Livewire::test(ComponentWithSessionModel::class)
247
+ + ->assertSet('article', fn ($article) => $article instanceof SessionArticle && $article->title === 'First');
248
+ +
249
+ + session()->save();
250
+ + session()->start();
251
+ +
252
+ + Livewire::test(ComponentWithSessionModel::class)
253
+ + ->assertSet('article', fn ($article) => $article instanceof SessionArticle && $article->title === 'First');
254
+ + }
255
+ +
256
+ + public function test_php_sessions_continue_to_store_values_raw()
257
+ + {
258
+ + config(['session.serialization' => 'php']);
259
+ +
260
+ + app('session')->forgetDrivers();
261
+ +
262
+ + Livewire::test(ComponentWithSessionCollection::class)
263
+ + ->call('add');
264
+ +
265
+ + $stored = session('collection');
266
+ +
267
+ + $this->assertInstanceOf(Collection::class, $stored);
268
+ + $this->assertSame([1], $stored->all());
269
+ + }
270
+ +
271
+ + public function test_json_sessions_continue_to_store_primitive_values_raw()
272
+ + {
273
+ + config(['session.serialization' => 'json']);
274
+ +
275
+ + app('session')->forgetDrivers();
276
+ +
277
+ + Livewire::test(ComponentWithPrimitiveSessionProperty::class)
278
+ + ->set('count', 1);
279
+ +
280
+ + $this->assertSame(1, session('primitive'));
281
+ + $this->assertSame(['search' => '', 'tags' => [1, 2]], session('json-native'));
282
+ + }
283
+ +
284
+ + public function test_legacy_tuple_shaped_arrays_are_not_treated_as_synthetic_values()
285
+ + {
286
+ + $tuple = [['one', 'two'], ['s' => 'clctn', 'class' => Collection::class]];
287
+ +
288
+ + FacadesSession::put('legacy-tuple', $tuple);
289
+ +
290
+ + Livewire::test(ComponentWithRawSessionArray::class)
291
+ + ->assertSet('value', $tuple);
292
+ + }
293
+ +
294
+ + public function test_session_envelopes_are_decoded_even_after_switching_to_php_serialization()
295
+ + {
296
+ + config(['session.serialization' => 'json']);
297
+ +
298
+ + app('session')->forgetDrivers();
299
+ +
300
+ + Livewire::test(ComponentWithSessionCollection::class)
301
+ + ->call('add');
302
+ +
303
+ + config(['session.serialization' => 'php']);
304
+ +
305
+ + Livewire::test(ComponentWithSessionCollection::class)
306
+ + ->assertSet('list', fn ($list) => $list instanceof Collection && $list->all() === [1]);
307
+ + }
308
+ +
309
+ + public function test_client_authored_synth_envelopes_are_discarded_in_json_sessions()
310
+ + {
311
+ + $this->assertClientAuthoredSynthEnvelopeIsDiscarded('json');
312
+ + }
313
+ +
314
+ + public function test_client_authored_synth_envelopes_are_discarded_in_php_sessions()
315
+ + {
316
+ + $this->assertClientAuthoredSynthEnvelopeIsDiscarded('php');
317
+ + }
318
+ +
319
+ + public function test_unreadable_persisted_envelopes_are_discarded()
320
+ + {
321
+ + config(['session.serialization' => 'json']);
322
+ +
323
+ + app('session')->forgetDrivers();
324
+ +
325
+ + Livewire::test(ComponentWithSessionCollection::class)
326
+ + ->call('add');
327
+ +
328
+ + $stored = session('collection');
329
+ + $stored[PersistedValueCodec::KEY]['version']++;
330
+ +
331
+ + FacadesSession::put('collection', $stored);
332
+ +
333
+ + Livewire::test(ComponentWithSessionCollection::class)
334
+ + ->assertSet('list', fn ($list) => $list instanceof Collection && $list->isEmpty());
335
+ + }
336
+ +
337
+ + public function test_components_can_share_an_explicit_session_key()
338
+ + {
339
+ + config(['session.serialization' => 'json']);
340
+ +
341
+ + app('session')->forgetDrivers();
342
+ +
343
+ + Livewire::test(ComponentWithSessionCollection::class)
344
+ + ->call('add');
345
+ +
346
+ + session()->save();
347
+ + session()->start();
348
+ +
349
+ + Livewire::test(ComponentReadingSharedSessionCollection::class)
350
+ + ->assertSet('items', fn ($items) => $items instanceof Collection && $items->all() === [1]);
351
+ + }
352
+ +
353
+ + public function test_values_for_synths_that_are_no_longer_registered_are_discarded()
354
+ + {
355
+ + config(['session.serialization' => 'json']);
356
+ +
357
+ + app('session')->forgetDrivers();
358
+ +
359
+ + $encoded = app(PersistedValueCodec::class)->encodeForStorage(
360
+ + new \Illuminate\Foundation\Auth\User,
361
+ + new TestComponent,
362
+ + 'value',
363
+ + 'dangerous-value',
364
+ + );
365
+ +
366
+ + FacadesSession::put('dangerous-value', $encoded);
367
+ +
368
+ + app()->instance(
369
+ + \Livewire\Mechanisms\HandleSynths\HandleSynths::class,
370
+ + new \Livewire\Mechanisms\HandleSynths\HandleSynths,
371
+ + );
372
+ +
373
+ + Livewire::test(ComponentWithDangerousSessionProperty::class)
374
+ + ->assertSet('value', 'safe');
375
+ + }
376
+ +
377
+ + public function test_json_arrays_left_by_older_versions_are_discarded_from_typed_properties()
378
+ + {
379
+ + config(['session.serialization' => 'json']);
380
+ +
381
+ + app('session')->forgetDrivers();
382
+ + FacadesSession::put('stale-collection', [1, 2]);
383
+ +
384
+ + Livewire::test(ComponentWithStaleSessionCollection::class)
385
+ + ->assertSet('list', null);
386
+ + }
387
+ +
388
+ + public function test_stale_enum_backing_values_are_discarded_from_typed_properties()
389
+ + {
390
+ + config(['session.serialization' => 'json']);
391
+ +
392
+ + app('session')->forgetDrivers();
393
+ +
394
+ + // A scalar backing an enum case that no longer exists (a removed or
395
+ + // renamed case, or a value written before the enum changed). Coercing
396
+ + // it throws a ValueError that must be recovered from, not surfaced.
397
+ + FacadesSession::put('stale-enum', 'archived');
398
+ +
399
+ + Livewire::test(ComponentWithSessionEnum::class)
400
+ + ->assertSet('status', null);
401
+ + }
402
+ +
403
+ + protected function assertClientAuthoredSynthEnvelopeIsDiscarded($serialization)
404
+ + {
405
+ + config(['session.serialization' => $serialization]);
406
+ +
407
+ + app('session')->forgetDrivers();
408
+ +
409
+ + Livewire::test(ComponentWithDangerousSessionProperty::class)
410
+ + ->set('value', [
411
+ + PersistedValueCodec::KEY => [
412
+ + 'version' => PersistedValueCodec::VERSION,
413
+ + 'value' => [null, [
414
+ + 's' => 'mdl',
415
+ + 'class' => \Illuminate\Foundation\Auth\User::class,
416
+ + 'key' => 1,
417
+ + ]],
418
+ + ],
419
+ + ]);
420
+ +
421
+ + session()->save();
422
+ + session()->start();
423
+ +
424
+ + Livewire::test(ComponentWithDangerousSessionProperty::class)
425
+ + ->assertSet('value', 'safe');
426
+ + }
427
+ +}
428
+ +
429
+ +class ComponentWithSessionCollection extends Component
430
+ +{
431
+ + #[Session(key: 'collection')]
432
+ + public ?Collection $list = null;
433
+ +
434
+ + public function mount(): void
435
+ + {
436
+ + $this->list ??= collect();
437
+ + }
438
+ +
439
+ + public function add(): void
440
+ + {
441
+ + $this->list->push($this->list->count() + 1);
442
+ + }
443
+ +
444
+ + public function render()
445
+ + {
446
+ + return '<div>{{ $list->implode(", ") }}</div>';
447
+ + }
448
+ +}
449
+ +
450
+ +class ComponentReadingSharedSessionCollection extends Component
451
+ +{
452
+ + #[Session(key: 'collection')]
453
+ + public ?Collection $items = null;
454
+ +
455
+ + public function mount(): void
456
+ + {
457
+ + $this->items ??= collect();
458
+ + }
459
+ +
460
+ + public function render()
461
+ + {
462
+ + return '<div></div>';
463
+ + }
464
+ +}
465
+ +
466
+ +class ComponentWithSynthesizedSessionProperties extends Component
467
+ +{
468
+ + #[Session]
469
+ + public ?Carbon $when = null;
470
+ +
471
+ + #[Session]
472
+ + public array $nested = [];
473
+ +
474
+ + public function render()
475
+ + {
476
+ + return '<div></div>';
477
+ + }
478
+ +}
479
+ +
480
+ +class ComponentWithCustomSynthesizedSessionProperty extends Component
481
+ +{
482
+ + #[Session]
483
+ + public ?CustomSessionValue $value = null;
484
+ +
485
+ + public function mount()
486
+ + {
487
+ + $this->value ??= new CustomSessionValue('persisted');
488
+ + }
489
+ +
490
+ + public function render()
491
+ + {
492
+ + return '<div></div>';
493
+ + }
494
+ +}
495
+ +
496
+ +class ComponentWithSessionModel extends Component
497
+ +{
498
+ + #[Session(key: 'article')]
499
+ + public ?SessionArticle $article = null;
500
+ +
501
+ + public function mount()
502
+ + {
503
+ + $this->article ??= SessionArticle::first();
504
+ + }
505
+ +
506
+ + public function render()
507
+ + {
508
+ + return '<div></div>';
509
+ + }
510
+ +}
511
+ +
512
+ +class SessionArticle extends Model
513
+ +{
514
+ + use Sushi;
515
+ +
516
+ + protected $rows = [
517
+ + ['title' => 'First'],
518
+ + ];
519
+ +}
520
+ +
521
+ +class CustomSessionValue
522
+ +{
523
+ + public function __construct(public string $value) {}
524
+ +}
525
+ +
526
+ +class CustomSessionValueSynth extends Synth
527
+ +{
528
+ + public static $key = 'session-value';
529
+ +
530
+ + public static function match($target)
531
+ + {
532
+ + return $target instanceof CustomSessionValue;
533
+ + }
534
+ +
535
+ + public function dehydrate($target)
536
+ + {
537
+ + return [$target->value, []];
538
+ + }
539
+ +
540
+ + public function hydrate($value)
541
+ + {
542
+ + return new CustomSessionValue($value);
543
+ + }
544
+ +}
545
+ +
546
+ +class ComponentWithPrimitiveSessionProperty extends Component
547
+ +{
548
+ + #[Session(key: 'primitive')]
549
+ + public int $count = 0;
550
+ +
551
+ + #[Session(key: 'json-native')]
552
+ + public array $filters = ['search' => '', 'tags' => [1, 2]];
553
+ +
554
+ + public function render()
555
+ + {
556
+ + return '<div></div>';
557
+ + }
558
+ +}
559
+ +
560
+ +class ComponentWithRawSessionArray extends Component
561
+ +{
562
+ + #[Session(key: 'legacy-tuple')]
563
+ + public array $value = [];
564
+ +
565
+ + public function render()
566
+ + {
567
+ + return '<div></div>';
568
+ + }
569
+ +}
570
+ +
571
+ +class ComponentWithDangerousSessionProperty extends Component
572
+ +{
573
+ + #[Session(key: 'dangerous-value')]
574
+ + public $value = 'safe';
575
+ +
576
+ + public function render()
577
+ + {
578
+ + return '<div></div>';
579
+ + }
580
+ +}
581
+ +
582
+ +class ComponentWithStaleSessionCollection extends Component
583
+ +{
584
+ + #[Session(key: 'stale-collection')]
585
+ + public ?Collection $list = null;
586
+ +
587
+ + public function render()
588
+ + {
589
+ + return '<div></div>';
590
+ + }
591
+ +}
592
+ +
593
+ +enum SessionStatus: string
594
+ +{
595
+ + case Draft = 'draft';
596
+ + case Published = 'published';
597
+ +}
598
+ +
599
+ +class ComponentWithSessionEnum extends Component
600
+ +{
601
+ + #[Session(key: 'stale-enum')]
602
+ + public ?SessionStatus $status = null;
603
+ +
604
+ + public function render()
605
+ + {
606
+ + return '<div></div>';
607
+ + }
608
+ }
tasks/livewire__livewire-10628/tests/test.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uxo pipefail
3
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
4
+ cd /workspace
5
+ mkdir -p /logs/verifier
6
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json
7
+ CAPTURE_DIR="$(mktemp -d)" || exit 1
8
+ trap 'rm -rf -- "$CAPTURE_DIR"' EXIT
9
+ if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 5eb0926a9c9bec02e44d02962991aa4e3e0ac2bb > "$CAPTURE_DIR/predicted.patch"; then
10
+ echo "0.0" > /logs/verifier/reward.txt
11
+ printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json
12
+ exit 0
13
+ fi
14
+ rm -f /logs/verifier/predicted.patch
15
+ cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch
16
+ : 'START_VERIFY_OUTPUT'
17
+ if ! python3 -I "$SCRIPT_DIR/verifier.py" \
18
+ "$SCRIPT_DIR/oracle.patch" \
19
+ "$CAPTURE_DIR/predicted.patch" \
20
+ "$SCRIPT_DIR/instruction.md"; then
21
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json
22
+ printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json
23
+ fi
24
+ : 'END_VERIFY_OUTPUT'
25
+ exit 0
tasks/livewire__livewire-10628/tests/verifier.py ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """In-container verifier for pr_diff tasks (6-component reward).
2
+
3
+ This module is the **standalone verifier** that runs inside the task's
4
+ Docker container, NOT a helper used at generation time. Generation emits
5
+ its source as ``tests/verifier.py``. Harbor delivers it at verify time,
6
+ and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
7
+
8
+ Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
9
+
10
+ format_valid (0 or 1) — predicted parses as a unified diff (guard)
11
+ size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...)
12
+ catches "rampage through the codebase"
13
+ file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard —
14
+ symmetric penalty over-punishes extras)
15
+ region_overlap ([0, 1]) — predicted hunks overlap oracle hunks
16
+ (strongest spatial-localization signal)
17
+ similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only
18
+ (no free credit for context lines)
19
+ llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?"
20
+ Anthropic Haiku by default; any OpenAI-
21
+ compatible server via ``R2E_JUDGE_ENDPOINT``.
22
+ null when the judge is unavailable
23
+ (no key or model, network, unreadable
24
+ reply) → ungraded, no reward file; a
25
+ reply without a valid score (refusal,
26
+ content filter, empty, no "score") → a
27
+ graded 0
28
+
29
+ Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from
30
+ the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task
31
+ pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).
32
+ Override per-task via ``task.toml.metadata`` or per-run via env vars
33
+ ``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /
34
+ ``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they
35
+ reach the verifier container).
36
+
37
+ Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model
38
+ (default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible
39
+ server (vLLM, Ollama, a gateway) and switches the request to
40
+ ``<endpoint>/chat/completions`` with a bearer token from
41
+ ``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted
42
+ servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default
43
+ route and is never sent to a custom endpoint.
44
+
45
+ Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40
46
+ when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a
47
+ charitable judge from inflating scores on wildly wrong-sized patches).
48
+
49
+ Outputs (mirrors `_pr_runtime_verifier.py` after #75):
50
+ /logs/verifier/reward.txt — single float (Harbor reads this);
51
+ graded runs only
52
+ /logs/verifier/reward-details.json — full component breakdown + status
53
+ (structured diagnostics; Harbor's `reward.json` schema is flat-numeric-
54
+ only, so the breakdown goes to the `reward-details.json` sidecar which
55
+ Harbor renders under Verifier Logs → Rewards)
56
+
57
+ Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,
58
+ ``urllib``, ``sys``. The same module is imported by the unit tests
59
+ under ``tests/test_pr_diff_verifier.py`` so the in-container behavior
60
+ stays in lockstep with what we test.
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import argparse
66
+ import difflib
67
+ import json
68
+ import math
69
+ import os
70
+ import re
71
+ import sys
72
+ import urllib.error
73
+ import urllib.request
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Parsing helpers (shared by multiple components)
77
+ # ---------------------------------------------------------------------------
78
+
79
+ _DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")
80
+ _HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
81
+ _FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")
82
+ _INDEX_RE = re.compile(r"^index ")
83
+
84
+
85
+ def file_paths(diff: str) -> set[str]:
86
+ """Return the set of ``b/<path>`` paths touched by a unified diff."""
87
+ paths: set[str] = set()
88
+ for line in diff.splitlines():
89
+ m = _DIFF_HEADER_RE.match(line)
90
+ if m:
91
+ paths.add(m.group(2))
92
+ return paths
93
+
94
+
95
+ def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]:
96
+ """For each touched file, return list of (start_line, end_line) ranges
97
+ on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``).
98
+ """
99
+ out: dict[str, list[tuple[int, int]]] = {}
100
+ current_file: str | None = None
101
+ for line in diff.splitlines():
102
+ m = _DIFF_HEADER_RE.match(line)
103
+ if m:
104
+ current_file = m.group(2)
105
+ out.setdefault(current_file, [])
106
+ continue
107
+ m = _HUNK_HEADER_RE.match(line)
108
+ if m and current_file is not None:
109
+ new_start = int(m.group(3))
110
+ new_count = int(m.group(4) or "1")
111
+ end = new_start + max(new_count - 1, 0)
112
+ out[current_file].append((new_start, end))
113
+ return out
114
+
115
+
116
+ def _normalize_changes_only(diff: str) -> list[str]:
117
+ """Return the +/- lines (the actual changes) for similarity scoring.
118
+
119
+ Drops:
120
+ - ``diff --git`` / ``index abc..def`` metadata
121
+ - ``@@ ... @@`` hunk markers (volatile line numbers)
122
+ - context lines (no +/- prefix) — these are unchanged code, scoring
123
+ them inflates similarity for trivial patches
124
+ Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity
125
+ stays in the comparison; normalizes off the tab+timestamp suffix git
126
+ sometimes appends.
127
+ """
128
+ out: list[str] = []
129
+ for line in diff.splitlines():
130
+ if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line):
131
+ continue
132
+ if _HUNK_HEADER_RE.match(line):
133
+ continue
134
+ if _FILE_MARKER_RE.match(line):
135
+ out.append(line.split("\t")[0].strip())
136
+ continue
137
+ # +/- lines (actual changes)
138
+ if line.startswith("+") or line.startswith("-"):
139
+ out.append(line)
140
+ return out
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Reward components
145
+ # ---------------------------------------------------------------------------
146
+
147
+
148
+ def format_valid(predicted: str) -> float:
149
+ """1.0 if the predicted text looks like a unified diff; else 0.0.
150
+
151
+ Requires both a ``diff --git`` header and at least one real +/- line
152
+ (not the ``---`` / ``+++`` file-marker lines).
153
+ """
154
+ if not predicted.strip():
155
+ return 0.0
156
+ has_header = False
157
+ has_change = False
158
+ for line in predicted.splitlines():
159
+ if _DIFF_HEADER_RE.match(line):
160
+ has_header = True
161
+ elif (line.startswith("+") or line.startswith("-")) and not line.startswith(
162
+ ("+++ ", "--- ")
163
+ ):
164
+ has_change = True
165
+ if has_header and has_change:
166
+ return 1.0
167
+ return 0.0
168
+
169
+
170
+ def file_targeting(oracle: str, predicted: str) -> float:
171
+ """F1 over the changed-file sets.
172
+
173
+ Why F1 instead of Jaccard:
174
+ - Missing an oracle file (FN) is a *big* failure.
175
+ - Touching one unrelated extra file (FP) is a small one.
176
+ - Jaccard punishes both equally, which over-penalizes the agent
177
+ for any extra exploration.
178
+ - F1 weights TP twice, giving partial credit when the agent finds
179
+ most-but-not-all of the oracle files even with some noise.
180
+
181
+ Returns 1.0 if both sides touch zero files (degenerate).
182
+ """
183
+ o = file_paths(oracle)
184
+ p = file_paths(predicted)
185
+ if not o and not p:
186
+ return 1.0
187
+ tp = len(o & p)
188
+ fn = len(o - p)
189
+ fp = len(p - o)
190
+ if tp == 0:
191
+ return 0.0
192
+ # F1 = 2·TP / (2·TP + FN + FP)
193
+ return (2 * tp) / (2 * tp + fn + fp)
194
+
195
+
196
+ def _count_loc_changes(diff: str) -> int:
197
+ """Number of real +/- lines (excluding file-marker lines)."""
198
+ n = 0
199
+ for line in diff.splitlines():
200
+ if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")):
201
+ n += 1
202
+ return n
203
+
204
+
205
+ def size_sanity(oracle: str, predicted: str) -> float:
206
+ """Penalize predicted patches that are wildly larger / smaller than the oracle.
207
+
208
+ Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``.
209
+ Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
210
+
211
+ This is the "don't rampage through the codebase" guard — a 200-line
212
+ diff for a 3-line oracle scores ~0.015 here even if every other
213
+ component looks OK.
214
+ """
215
+ o_loc = _count_loc_changes(oracle)
216
+ p_loc = _count_loc_changes(predicted)
217
+ if o_loc == 0 and p_loc == 0:
218
+ return 1.0
219
+ if o_loc == 0 or p_loc == 0:
220
+ return 0.0
221
+ return min(o_loc, p_loc) / max(o_loc, p_loc)
222
+
223
+
224
+ def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float:
225
+ """For each oracle hunk, did the predicted diff edit a line within
226
+ ``slack_lines`` of that hunk in the same file?
227
+
228
+ Returns the fraction of oracle hunks that have at least one matching
229
+ predicted hunk. ``slack_lines`` tolerates slight line-number drift
230
+ when git diff renders the predicted hunk at a different offset.
231
+ """
232
+ o_ranges = hunk_ranges(oracle)
233
+ p_ranges = hunk_ranges(predicted)
234
+ total = sum(len(v) for v in o_ranges.values())
235
+ if total == 0:
236
+ return 1.0 # oracle has no hunks (degenerate)
237
+ matched = 0
238
+ for fname, ranges in o_ranges.items():
239
+ p_in_file = p_ranges.get(fname, [])
240
+ for o_start, o_end in ranges:
241
+ for p_start, p_end in p_in_file:
242
+ # Interval overlap with slack — max(starts) <= min(ends) + slack
243
+ if max(o_start, p_start) <= min(o_end, p_end) + slack_lines:
244
+ matched += 1
245
+ break
246
+ return matched / total
247
+
248
+
249
+ def similarity(oracle: str, predicted: str) -> float:
250
+ """SequenceMatcher ratio over +/- lines only.
251
+
252
+ No free credit for context lines — fixes the v0.8.1 inflation where a
253
+ one-line fix scored ~0.7 just because the 3 context lines on either
254
+ side were "matched".
255
+ """
256
+ if not predicted.strip():
257
+ return 0.0
258
+ o = _normalize_changes_only(oracle)
259
+ p = _normalize_changes_only(predicted)
260
+ if not o:
261
+ return 0.0
262
+ # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000
263
+ # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can
264
+ # run the verifier past Harbor's timeout. Above this many line pairs,
265
+ # fall back to difflib's popular-element heuristic, which stays fast.
266
+ exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS
267
+ return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
268
+
269
+
270
+ _SIMILARITY_EXACT_PAIRS = 400_000
271
+
272
+ # A predicted patch over 10x the oracle's changed lines is already a
273
+ # catastrophic size mismatch (size_sanity < 0.10). Past this floor such a
274
+ # patch is a graded 0 instead of being scored, so one huge file can't slow
275
+ # the verifier past its timeout and turn a failing episode into a dropped,
276
+ # ungraded one. The byte cap stops it from being read at all.
277
+ _MAX_PREDICTED_FACTOR = 10
278
+ _MAX_PREDICTED_FLOOR_LOC = 1_000
279
+ _MAX_PREDICTED_BYTES = 16 * 1024 * 1024
280
+
281
+
282
+ def predicted_too_large(oracle: str, predicted: str) -> bool:
283
+ """Whether the predicted patch is too large to score (a graded 0)."""
284
+ limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC)
285
+ return _count_loc_changes(predicted) > limit
286
+
287
+
288
+ # ---------------------------------------------------------------------------
289
+ # LLM-as-judge (Anthropic Messages API, stdlib urllib)
290
+ # ---------------------------------------------------------------------------
291
+
292
+
293
+ _JUDGE_PROMPT = (
294
+ "You are scoring a code-fix patch on whether it logically addresses the "
295
+ "described issue. Output a single JSON object: "
296
+ '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n'
297
+ "DO NOT use the oracle to grade. Score on:\n"
298
+ " - Does the predicted diff touch code regions that could plausibly fix the issue?\n"
299
+ " - Is the change direction consistent with what the issue describes?\n"
300
+ " - Is it a real attempt (not boilerplate, not no-op)?\n\n"
301
+ "Issue:\n{instruction}\n\n"
302
+ "Oracle (reference fix for comparison only — don't grade on similarity to it):\n"
303
+ "{oracle}\n\n"
304
+ "Predicted:\n{predicted}\n\n"
305
+ "Return ONLY the JSON object."
306
+ )
307
+
308
+
309
+ _DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"
310
+ _ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"
311
+ # Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /
312
+ # Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses.
313
+ _PLACEHOLDER_API_KEY = "EMPTY"
314
+
315
+
316
+ def llm_judge(
317
+ *,
318
+ instruction: str,
319
+ oracle: str,
320
+ predicted: str,
321
+ api_key: str,
322
+ model: str = _DEFAULT_JUDGE_MODEL,
323
+ timeout: int = 60,
324
+ endpoint: str | None = None,
325
+ ) -> tuple[float | None, str]:
326
+ """Return ``(score, status)``.
327
+
328
+ ``score`` is a float in [0, 1] on success, ``None`` on failure.
329
+ ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` /
330
+ ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` /
331
+ ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``.
332
+ ``output_limit`` means the judge exhausted its configured token budget
333
+ (ungraded, even if a partial answer contains a score). ``parse`` means
334
+ the provider's body isn't JSON or has the wrong shape (ungraded); a reply
335
+ with no usable text (refusal, content filter, empty) or no valid score is
336
+ ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never
337
+ increases the other weights.
338
+
339
+ ``endpoint`` — base URL of an OpenAI-compatible server. When set, the
340
+ request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a
341
+ bearer token, at temperature 0, and ``model`` must be given explicitly;
342
+ otherwise it goes to Anthropic's Messages API unchanged.
343
+ """
344
+ if not api_key:
345
+ return None, "no_api_key"
346
+ if endpoint and not model:
347
+ return None, "no_judge_model"
348
+ if not predicted.strip():
349
+ return 0.0, "empty_predicted"
350
+
351
+ # Truncate hard so we don't blow up the prompt for big diffs
352
+ prompt = _JUDGE_PROMPT.format(
353
+ instruction=instruction[:4000],
354
+ oracle=oracle[:4000],
355
+ predicted=predicted[:4000],
356
+ )
357
+ payload: dict = {
358
+ "model": model,
359
+ "max_tokens": 200,
360
+ "messages": [{"role": "user", "content": prompt}],
361
+ }
362
+ if endpoint:
363
+ # Small self-hosted models are noisy judges at their default sampling
364
+ # temperature (same input scoring 0.0 one call and 1.0 the next); pin
365
+ # them to greedy. The Anthropic route keeps its defaults — the weights
366
+ # were calibrated against them.
367
+ payload["temperature"] = 0
368
+ url = endpoint.rstrip("/") + "/chat/completions"
369
+ headers = {
370
+ "authorization": f"Bearer {api_key}",
371
+ "content-type": "application/json",
372
+ }
373
+ else:
374
+ url = _ANTHROPIC_MESSAGES_URL
375
+ headers = {
376
+ "x-api-key": api_key,
377
+ "anthropic-version": "2023-06-01",
378
+ "content-type": "application/json",
379
+ }
380
+ body = json.dumps(payload).encode("utf-8")
381
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
382
+ try:
383
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
384
+ raw = resp.read().decode("utf-8")
385
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError):
386
+ return None, "network"
387
+
388
+ try:
389
+ response = json.loads(raw)
390
+ except json.JSONDecodeError:
391
+ return None, "parse"
392
+ # Provider-reported truncation is a grader capacity failure, not evidence
393
+ # that the submitted patch is wrong. Reasoning models can spend the entire
394
+ # output budget before producing visible text. Never grade a partial score.
395
+ if isinstance(response, dict):
396
+ choices = response.get("choices")
397
+ if endpoint:
398
+ if (
399
+ isinstance(choices, list)
400
+ and choices
401
+ and isinstance(choices[0], dict)
402
+ and choices[0].get("finish_reason") == "length"
403
+ ):
404
+ return None, "output_limit"
405
+ elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}:
406
+ return None, "output_limit"
407
+ text = _judge_text(response, openai_compatible=bool(endpoint))
408
+ if text is None:
409
+ return None, "parse"
410
+
411
+ # Pull the first JSON object out of the model's response
412
+ m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL)
413
+ if not m:
414
+ return None, "missing_score"
415
+ try:
416
+ obj = json.loads(m.group(0))
417
+ score = obj.get("score")
418
+ except (json.JSONDecodeError, ValueError, TypeError):
419
+ return None, "missing_score"
420
+ if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score):
421
+ return None, "invalid_score"
422
+ return float(score), "ok"
423
+
424
+
425
+ def _judge_text(payload: object, *, openai_compatible: bool) -> str | None:
426
+ """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
427
+
428
+ A refusal or a content filter is a well-formed reply with no usable text.
429
+ The agent's patch is in the prompt, so it can provoke one: that is ``""``,
430
+ which grades 0, not ``None``, which leaves the run ungraded.
431
+
432
+ Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and
433
+ ``content`` empty or holding partial text to discard. OpenAI-compatible:
434
+ ``message.content`` is null with a ``refusal`` string or
435
+ ``finish_reason: "content_filter"``.
436
+ """
437
+ if not isinstance(payload, dict):
438
+ return None
439
+ if openai_compatible:
440
+ choices = payload.get("choices")
441
+ if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
442
+ return None
443
+ message = choices[0].get("message")
444
+ if not isinstance(message, dict):
445
+ return None
446
+ if message.get("refusal") or choices[0].get("finish_reason") == "content_filter":
447
+ return ""
448
+ content = message.get("content")
449
+ if content is None:
450
+ return ""
451
+ if isinstance(content, str):
452
+ return content
453
+ if isinstance(content, list): # content parts
454
+ return "".join(
455
+ part.get("text", "")
456
+ for part in content
457
+ if isinstance(part, dict) and isinstance(part.get("text", ""), str)
458
+ )
459
+ return None
460
+ content = payload.get("content")
461
+ if not isinstance(content, list):
462
+ return None
463
+ if payload.get("stop_reason") == "refusal":
464
+ return ""
465
+ return "".join(
466
+ block["text"]
467
+ for block in content
468
+ if isinstance(block, dict)
469
+ and block.get("type", "text") == "text"
470
+ and isinstance(block.get("text"), str)
471
+ )
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # Combination
476
+ # ---------------------------------------------------------------------------
477
+
478
+
479
+ # Judge replies the agent can provoke: its patch text is part of the judge
480
+ # prompt, so it can steer the answer away from a valid score. These are a
481
+ # graded 0. An unreadable provider envelope (`parse`), missing configuration,
482
+ # a disabled judge, transport errors and an exhausted judge output budget leave
483
+ # the evaluation ungraded. Truncation alone cannot establish an incorrect patch.
484
+ _JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
485
+
486
+
487
+ def evaluation_status(judge_score: float | None, judge_status: str) -> str:
488
+ """`graded` when the judge scored or the agent can have caused its failure."""
489
+ if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO:
490
+ return "graded"
491
+ return "ungraded"
492
+
493
+
494
+ def combine(components: dict[str, float | None], weights: dict[str, float]) -> float:
495
+ """Combine declared components, requiring a positively weighted judge.
496
+
497
+ Without a judge score the result is 0. ``main`` records it as a graded 0
498
+ when the agent can have caused the judge failure, and otherwise writes no
499
+ reward file, so Harbor reports the trial as VERIFIER_FAILED.
500
+ """
501
+ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None:
502
+ return 0.0
503
+ if any(w > 0 and components.get(k) is None for k, w in weights.items()):
504
+ return 0.0
505
+ return _weighted_mean(components, weights)
506
+
507
+
508
+ def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float:
509
+ available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None]
510
+ if not available:
511
+ return 0.0
512
+ # Relative weights need not sum to one. Scale first so large finite
513
+ # overrides cannot overflow the numerator or denominator into NaN.
514
+ scale = max(w for _, w in available)
515
+ normalized = [(k, w / scale) for k, w in available]
516
+ return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
517
+
518
+
519
+ # ---------------------------------------------------------------------------
520
+ # Entry point (invoked by tests/test.sh inside the container)
521
+ # ---------------------------------------------------------------------------
522
+
523
+
524
+ # Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer
525
+ # analysis grounded in per-task component data):
526
+ #
527
+ # - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero
528
+ # discriminative signal — its 0.05 weight was pure dead weight.
529
+ # - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.
530
+ # Carrying both at 0.20 double-counts positional accuracy and
531
+ # additionally penalizes legitimate alternative implementations.
532
+ # - llm_judge → 0.50: only component capturing semantic correctness
533
+ # independent of textual form; diverges informatively from
534
+ # similarity on cases like tokenizers (judge=0.72, sim=0.08).
535
+ # - region_overlap stays 0.20: strongest spatial-localization signal.
536
+ # - file_targeting → 0.12: leading indicator, less correlated with the
537
+ # rest than region/similarity are with each other.
538
+ # - size_sanity → 0.08: useful outlier detector for catastrophic
539
+ # over/under-generation (prettier=0.01, serde=0.08).
540
+ #
541
+ # Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00.
542
+ _DEFAULT_WEIGHTS = {
543
+ "format_valid": 0.00,
544
+ "size_sanity": 0.08,
545
+ "file_targeting": 0.12,
546
+ "region_overlap": 0.20,
547
+ "similarity": 0.10,
548
+ "llm_judge": 0.50,
549
+ }
550
+
551
+ # Hard cap: when size_sanity < this threshold, clamp final reward to
552
+ # ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating
553
+ # the score on patches that are wildly the wrong size (catastrophic
554
+ # over- or under-generation).
555
+ _CATASTROPHIC_SIZE_THRESHOLD = 0.10
556
+ _CATASTROPHIC_SIZE_CAP = 0.40
557
+
558
+
559
+ def _read_weights_from_env() -> dict[str, float]:
560
+ """Override defaults via R2E_W_* env vars (set in container by harbor)."""
561
+ overrides = {
562
+ "format_valid": os.environ.get("R2E_W_FORMAT"),
563
+ "size_sanity": os.environ.get("R2E_W_SIZE"),
564
+ "file_targeting": os.environ.get("R2E_W_FILE"),
565
+ "region_overlap": os.environ.get("R2E_W_REGION"),
566
+ "similarity": os.environ.get("R2E_W_SIM"),
567
+ "llm_judge": os.environ.get("R2E_W_JUDGE"),
568
+ }
569
+ out = dict(_DEFAULT_WEIGHTS)
570
+ for k, v in overrides.items():
571
+ if v is None:
572
+ continue
573
+ try:
574
+ value = float(v)
575
+ if math.isfinite(value) and value >= 0:
576
+ out[k] = value
577
+ except (TypeError, ValueError):
578
+ continue
579
+ return out
580
+
581
+
582
+ def _judge_config_from_env() -> tuple[str, str, str | None]:
583
+ """``(api_key, model, endpoint)`` for the judge, from the verifier env.
584
+
585
+ With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY``
586
+ (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to
587
+ the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a
588
+ self-hosted server won't have Haiku): when unset, ``model`` comes back
589
+ as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of
590
+ calling out. Without an endpoint the default Anthropic route is
591
+ unchanged.
592
+ """
593
+ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None
594
+ model = os.environ.get("R2E_JUDGE_MODEL", "").strip()
595
+ if endpoint:
596
+ api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY
597
+ return api_key, model, endpoint
598
+ return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
599
+
600
+
601
+ def main(argv: list[str] | None = None) -> int:
602
+ parser = argparse.ArgumentParser(description=__doc__)
603
+ parser.add_argument("oracle")
604
+ parser.add_argument("predicted")
605
+ parser.add_argument("instruction")
606
+ parser.add_argument("--out-dir", default="/logs/verifier")
607
+ args = parser.parse_args(argv)
608
+ os.makedirs(args.out_dir, exist_ok=True)
609
+ # This run is the only authority on the reward: an earlier or planted
610
+ # reward file must not stand if this evaluation ends up ungraded.
611
+ for name in ("reward.txt", "reward.json"):
612
+ try:
613
+ os.unlink(os.path.join(args.out_dir, name))
614
+ except FileNotFoundError:
615
+ pass
616
+ oracle = _read_or_empty(args.oracle)
617
+ try:
618
+ oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES
619
+ except OSError:
620
+ oversized = False
621
+ predicted = "" if oversized else _read_or_empty(args.predicted)
622
+ if oversized or predicted_too_large(oracle, predicted):
623
+ breakdown = {
624
+ "final_reward": 0.0,
625
+ "evaluation_status": "graded",
626
+ "eval_trustworthy": False,
627
+ "predicted_status": "predicted_too_large",
628
+ }
629
+ _write_outputs(args.out_dir, 0.0, breakdown)
630
+ return 0
631
+ instruction = _read_or_empty(args.instruction)
632
+ api_key, judge_model, judge_endpoint = _judge_config_from_env()
633
+
634
+ fv = format_valid(predicted)
635
+ ss = size_sanity(oracle, predicted)
636
+ ft = file_targeting(oracle, predicted)
637
+ ro = region_overlap(oracle, predicted)
638
+ sim = similarity(oracle, predicted)
639
+ weights = _read_weights_from_env()
640
+ if weights["llm_judge"] <= 0:
641
+ judge_score, judge_status = None, "disabled"
642
+ else:
643
+ judge_score, judge_status = llm_judge(
644
+ instruction=instruction,
645
+ oracle=oracle,
646
+ predicted=predicted,
647
+ api_key=api_key,
648
+ model=judge_model,
649
+ endpoint=judge_endpoint,
650
+ )
651
+
652
+ components: dict[str, float | None] = {
653
+ "format_valid": fv,
654
+ "size_sanity": ss,
655
+ "file_targeting": ft,
656
+ "region_overlap": ro,
657
+ "similarity": sim,
658
+ "llm_judge": judge_score,
659
+ }
660
+ final = combine(components, weights)
661
+ final = max(0.0, min(1.0, final))
662
+
663
+ # Hard cap on catastrophic size mismatches. Without this, a charitable
664
+ # judge can inflate the reward on patches that are dramatically the
665
+ # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge
666
+ # was lenient at 0.25 despite the patch being a near-no-op vs a
667
+ # 500-line oracle). The cap kicks in only at the extremes.
668
+ if ss < _CATASTROPHIC_SIZE_THRESHOLD:
669
+ final = min(final, _CATASTROPHIC_SIZE_CAP)
670
+
671
+ status = evaluation_status(judge_score, judge_status)
672
+ breakdown = {
673
+ # No reward exists for an ungraded evaluation: null, not a placeholder 0.
674
+ "final_reward": round(final, 6) if status == "graded" else None,
675
+ "evaluation_status": status,
676
+ "eval_trustworthy": judge_score is not None,
677
+ "diagnostic_similarity": round(
678
+ _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}),
679
+ 6,
680
+ ),
681
+ "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()},
682
+ "weights": {k: round(v, 6) for k, v in weights.items()},
683
+ "judge_model": judge_model if judge_status == "ok" else None,
684
+ "judge_endpoint": judge_endpoint,
685
+ "judge_status": judge_status,
686
+ }
687
+
688
+ _write_outputs(args.out_dir, final, breakdown)
689
+ return 0
690
+
691
+
692
+ def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None:
693
+ # An ungraded evaluation writes no reward file. Harbor then raises
694
+ # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is
695
+ # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout
696
+ # instead of training on a 0. Harbor's job mean and pass@k still count the
697
+ # trial as 0, so evaluation stays fail-closed.
698
+ if breakdown["evaluation_status"] == "graded":
699
+ with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f:
700
+ f.write(f"{final:.6f}\n")
701
+ # Harbor's `reward.json` must be a flat map of floats/ints (spec, see
702
+ # <https://harborframework.com/docs/tasks>); our breakdown carries nested
703
+ # dicts, judge strings, and status strings, so it goes to the sidecar the
704
+ # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig)
705
+ # for `_pr_runtime_verifier.py`.
706
+ with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f:
707
+ json.dump(breakdown, f, indent=2)
708
+
709
+ # Also print to stdout so harbor's log captures the breakdown
710
+ print(json.dumps(breakdown, indent=2))
711
+
712
+
713
+ def _read_or_empty(path: str) -> str:
714
+ try:
715
+ with open(path, encoding="utf-8") as f:
716
+ return f.read()
717
+ except (OSError, UnicodeDecodeError):
718
+ return ""
719
+
720
+
721
+ if __name__ == "__main__":
722
+ sys.exit(main())
723
+
724
+
725
+ __all__ = [
726
+ "combine",
727
+ "file_paths",
728
+ "file_targeting",
729
+ "format_valid",
730
+ "hunk_ranges",
731
+ "llm_judge",
732
+ "main",
733
+ "predicted_too_large",
734
+ "region_overlap",
735
+ "similarity",
736
+ "size_sanity",
737
+ ]
tasks/livewire__livewire-10629/environment/Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.
2
+ # Agent-agnostic: the agent (claude-code / openhands / codex / etc.)
3
+ # installs itself at run time via its harbor adapter. We only ship
4
+ # the source repo — the oracle + verifier arrive at verify time via
5
+ # tests/, never baked into the agent's image.
6
+ FROM python:3.12-slim
7
+ ARG GITHUB_TOKEN=
8
+ RUN apt-get update \
9
+ && apt-get install -y --no-install-recommends git ca-certificates curl \
10
+ && rm -rf /var/lib/apt/lists/*
11
+ RUN git config --global --add safe.directory /workspace \
12
+ && git config --global init.defaultBranch main \
13
+ && git config --global advice.detachedHead false
14
+ RUN if [ -n "$GITHUB_TOKEN" ]; then \
15
+ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin db3f789c8fa5ed49a7e1a785e6b0355d6304ec95 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard db3f789c8fa5ed49a7e1a785e6b0355d6304ec95 \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base db3f789c8fa5ed49a7e1a785e6b0355d6304ec95 \
26
+ && git remote remove origin 2>/dev/null || true
27
+ RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \
28
+ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \
29
+ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \
30
+ && git reflog expire --expire=now --all 2>/dev/null || true \
31
+ && git gc --prune=now 2>/dev/null || true
32
+ RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \
33
+ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \
34
+ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \
35
+ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \
36
+ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \
37
+ fi
tasks/livewire__livewire-10629/instruction.md ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** [4.x] Fix wire transition skipped after flux toast auto-dismissed
4
+
5
+ ## Description
6
+
7
+ ### Problem
8
+
9
+ `wire:transition` currently skips a View Transition whenever there is an open modal dialog or popover:
10
+
11
+ ```js
12
+ if (document.querySelector('dialog:modal, :popover-open')) {
13
+ return callback()
14
+ }
15
+ ```
16
+
17
+ This is necessary for open popovers because View Transition pseudo-elements can paint above the top layer. Starting a transition while a popover is open can cause the transition to render over the popover.
18
+
19
+ However, `:popover-open` only tells us that the popover itself is open. It does not tell us whether the popover currently has any **visible UI**.
20
+
21
+ Some components keep a popover open as a persistent container while its contents are hidden. In that case, `:popover-open` still matches even though there is nothing visible that needs to be protected from the View Transition.
22
+
23
+ This causes subsequent Livewire transitions to be skipped unnecessarily.
24
+
25
+ ### Solution
26
+
27
+ Keep the existing behavior for modal dialogs, but for popovers only skip the transition when the popover contains a visible element:
28
+
29
+ ```js
30
+ if (document.querySelector('dialog:modal')) return callback()
31
+
32
+ for (let popover of document.querySelectorAll(':popover-open')) {
33
+ for (let el of popover.querySelectorAll('*')) {
34
+ if (el.checkVisibility()) return callback()
35
+ }
36
+ }
37
+ ```
38
+
39
+ `checkVisibility()` lets us determine whether the open popover actually contains visible UI without relying on any framework- or component-specific selectors.
40
+
41
+ This keeps the behavior generic and avoids coupling Livewire's transition implementation to a particular component library or DOM structure.
42
+
43
+ ### Why not just check `:popover-open`?
44
+
45
+ An open popover can remain mounted and open while its contents are hidden. Treating every `:popover-open` element as blocking would therefore incorrectly skip transitions when there is no visible popover.
46
+
47
+ At the same time, removing the `:popover-open` check entirely would reintroduce the issue where an actually visible popover can be covered by View Transition pseudo-elements.
48
+
49
+ The new check handles both cases:
50
+
51
+ * **Visible popover** → skip the transition.
52
+ * **Open but visually inactive popover** → allow the transition.
53
+ * **Modal dialog** → skip the transition as before.
54
+
55
+ ### Why `checkVisibility()`?
56
+
57
+ Checking text content, child count, or specific element names would be unreliable:
58
+
59
+ * A popover can contain non-textual UI.
60
+ * A popover can contain DOM nodes that are hidden.
61
+ * Empty/non-empty DOM structure does not necessarily correspond to visible UI.
62
+ * Component-specific selectors would couple Livewire to another package's implementation details.
63
+
64
+ `checkVisibility()` directly answers the relevant question: whether there is currently a visible element inside the open popover.
65
+
66
+ Fixes:
67
+
68
+ ## Task
69
+
70
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `db3f789c8fa5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/livewire__livewire-10629/solution/patch.diff ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/js/directives/wire-transition.js b/js/directives/wire-transition.js
2
+ index fc61399d..3cf56e58 100644
3
+ --- a/js/directives/wire-transition.js
4
+ +++ b/js/directives/wire-transition.js
5
+ @@ -44,7 +44,18 @@ export async function transitionDomMutation(fromEl, toEl, callback, options = {}
6
+ // Skip entirely if a top-layer element is already open (transitions behind
7
+ // it are invisible to the user and the ::view-transition pseudo-elements
8
+ // would paint above it during animation)...
9
+ - if (document.querySelector('dialog:modal, :popover-open')) return callback()
10
+ + if (document.querySelector('dialog:modal')) return callback()
11
+ +
12
+ + // An open popover only blocks the transition if it has visible descendants.
13
+ + // Some components (e.g. toast hosts) keep an empty popover open as a
14
+ + // persistent container — the host element itself always passes
15
+ + // checkVisibility() while open, so visible *descendants* are the proxy
16
+ + // for "this popover is actually showing UI"...
17
+ + for (let popover of document.querySelectorAll(':popover-open')) {
18
+ + for (let el of popover.querySelectorAll('*')) {
19
+ + if (el.checkVisibility()) return callback()
20
+ + }
21
+ + }
22
+
23
+ // Set transition names right before the transition starts (not permanently)...
24
+ setTransitionNames(fromEl, options)
25
+ diff --git a/src/Features/SupportTransitions/BrowserTest.php b/src/Features/SupportTransitions/BrowserTest.php
26
+ index 0622e9db..f6f50daa 100644
27
+ --- a/src/Features/SupportTransitions/BrowserTest.php
28
+ +++ b/src/Features/SupportTransitions/BrowserTest.php
29
+ @@ -500,4 +500,92 @@ class BrowserTest extends \Tests\BrowserTestCase
30
+ ->waitUntil("!$animationsRunning")
31
+ ;
32
+ }
33
+ +
34
+ + public function test_transition_runs_when_popover_stays_open_without_visible_content()
35
+ + {
36
+ + Livewire::visit(
37
+ + new class extends \Livewire\Component {
38
+ + public $show = false;
39
+ +
40
+ + public function toggle()
41
+ + {
42
+ + $this->show = ! $this->show;
43
+ + }
44
+ +
45
+ + public function render()
46
+ + {
47
+ + return <<<'HTML'
48
+ + <div>
49
+ + <button wire:click="toggle" dusk="toggle">Toggle</button>
50
+ +
51
+ + @if ($show)
52
+ + <div wire:transition dusk="target">Hello</div>
53
+ + @endif
54
+ +
55
+ + <div popover="manual" dusk="toast-host" x-init="$el.showPopover()">
56
+ + <template>
57
+ + <div>Hidden popover content</div>
58
+ + </template>
59
+ + </div>
60
+ + </div>
61
+ + HTML;
62
+ + }
63
+ + }
64
+ + )
65
+ + ->waitUntil("document.querySelector('[dusk=toast-host]').matches(':popover-open')")
66
+ + ->tap(fn ($browser) => $browser->script("
67
+ + window.__startViewTransitionCalled = false
68
+ + let original = document.startViewTransition.bind(document)
69
+ + document.startViewTransition = function (...args) {
70
+ + window.__startViewTransitionCalled = true
71
+ + return original(...args)
72
+ + }
73
+ + "))
74
+ + ->waitForLivewire()->click('@toggle')
75
+ + ->waitFor('@target')
76
+ + ->assertScript('window.__startViewTransitionCalled', true);
77
+ + }
78
+ +
79
+ + public function test_transition_does_not_run_when_popover_has_visible_content()
80
+ + {
81
+ + Livewire::visit(
82
+ + new class extends \Livewire\Component {
83
+ + public $show = false;
84
+ +
85
+ + public function toggle()
86
+ + {
87
+ + $this->show = ! $this->show;
88
+ + }
89
+ +
90
+ + public function render()
91
+ + {
92
+ + return <<<'HTML'
93
+ + <div>
94
+ + <button wire:click="toggle" dusk="toggle">Toggle</button>
95
+ +
96
+ + @if ($show)
97
+ + <div wire:transition dusk="target">Hello</div>
98
+ + @endif
99
+ +
100
+ + <div popover="manual" dusk="toast-host" x-init="$el.showPopover()">
101
+ + <div>Visible popover content</div>
102
+ + </div>
103
+ + </div>
104
+ + HTML;
105
+ + }
106
+ + }
107
+ + )
108
+ + ->waitUntil("document.querySelector('[dusk=toast-host]').matches(':popover-open')")
109
+ + ->tap(fn ($browser) => $browser->script("
110
+ + window.__startViewTransitionCalled = false
111
+ + let original = document.startViewTransition.bind(document)
112
+ + document.startViewTransition = function (...args) {
113
+ + window.__startViewTransitionCalled = true
114
+ + return original(...args)
115
+ + }
116
+ + "))
117
+ + ->waitForLivewire()->click('@toggle')
118
+ + ->waitFor('@target')
119
+ + ->assertScript('window.__startViewTransitionCalled', false);
120
+ + }
121
+ }
tasks/livewire__livewire-10629/solution/solve.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euxo pipefail
3
+ cd /workspace
4
+ git config --global --add safe.directory /workspace
5
+ PATCH="$(dirname "$0")/patch.diff"
6
+ git apply --verbose --reject "$PATCH"
tasks/livewire__livewire-10629/task.toml ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/livewire__livewire-10629"
5
+ description = "[4.x] Fix wire transition skipped after flux toast auto-dismissed"
6
+
7
+ [metadata]
8
+ difficulty = "large"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "livewire",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "livewire/livewire"
19
+ ref = "db3f789c8fa5ed49a7e1a785e6b0355d6304ec95"
20
+ reference = "https://github.com/livewire/livewire/pull/10629"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:51.538746+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:a63b2addca6b4e10ce4848d1ae54c588acdb3d1828476111b96cd3c36bb37de5"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-08-30T12:09:17Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "js/directives/wire-transition.js",
34
+ "src/Features/SupportTransitions/BrowserTest.php",
35
+ ]
36
+ bootstrap_image = "python:3.12-slim"
37
+
38
+ [metadata.repo2env.reward_calibration]
39
+ baseline_reward = 0.0
40
+ loc_changed = 101
41
+ difficulty = "large"
42
+
43
+ [metadata.repo2env.evaluation]
44
+ schema_version = "1"
45
+ status = "unverified"
46
+ stage = "generation"
47
+ reason_codes = [
48
+ "validation_not_run",
49
+ ]
50
+ detail = "Generated task; validation has not been established."
51
+ provenance = "unknown"
52
+ evidence = []
53
+
54
+ [metadata.repo2env.reproducibility]
55
+ mode = "inline_dockerfile"
56
+ image_ref = "python:3.12-slim"
57
+ image_tag = "python:3.12-slim"
58
+ image_visibility = "public"
59
+ pushed_at = "2026-11-16T16:20:01.367411+00:00"
60
+ pushed_by = "scalingX"
61
+ inline_recipe_sha256 = "sha256:1cc3933f3d663792f5ca2038cb48f521c16715f1543ec9f72f4519964d0e8399"
62
+ inline_recipe_lines = 37
63
+ inline_recipe_source = "user_dockerfile"
64
+
65
+ [agent]
66
+ timeout_sec = 1800.0
67
+
68
+ [verifier]
69
+ timeout_sec = 300.0
tasks/livewire__livewire-10629/tests/capture.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone PR-diff capture without executing workspace Git configuration.
2
+
3
+ The emitted task uses a regular clone with a pinned base commit. Only its
4
+ object store is read: refs, index, config, hooks and replacement refs are not
5
+ used. This is a configuration boundary, not a sandbox for a malicious process
6
+ that can modify the verifier, binaries or object store while capture runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+
22
+ def capture(workspace: Path, base_commit: str) -> bytes:
23
+ """Capture tracked and new files through a fresh private Git index."""
24
+ if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit):
25
+ raise ValueError("Expected the task's pinned SHA-1 base commit")
26
+ objects = workspace.resolve() / ".git" / "objects"
27
+ if not objects.is_dir():
28
+ raise ValueError("The task's cloned Git object store is missing")
29
+ git = shutil.which("git", path=os.defpath)
30
+ if git is None:
31
+ raise FileNotFoundError("System git is unavailable")
32
+ with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary:
33
+ private = Path(temporary)
34
+ # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs,
35
+ # system/global includes, user attributes, templates or credential env.
36
+ env = {
37
+ "PATH": os.defpath,
38
+ "HOME": temporary,
39
+ "XDG_CONFIG_HOME": temporary,
40
+ "GIT_CONFIG_NOSYSTEM": "1",
41
+ "GIT_CONFIG_GLOBAL": os.devnull,
42
+ "GIT_ATTR_NOSYSTEM": "1",
43
+ "GIT_NO_REPLACE_OBJECTS": "1",
44
+ "GIT_NO_LAZY_FETCH": "1",
45
+ "GIT_TERMINAL_PROMPT": "0",
46
+ "LC_ALL": "C",
47
+ }
48
+ subprocess.run(
49
+ [git, "init", "--quiet", "--template=", str(private / "repository")],
50
+ env=env,
51
+ cwd=private,
52
+ check=True,
53
+ capture_output=True,
54
+ timeout=60,
55
+ )
56
+ env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False)
57
+ command = [
58
+ git,
59
+ f"--git-dir={private / 'repository/.git'}",
60
+ f"--work-tree={workspace.resolve()}",
61
+ ]
62
+
63
+ def run(*args: str) -> bytes:
64
+ return subprocess.run(
65
+ [*command, *args],
66
+ env=env,
67
+ cwd=workspace,
68
+ check=True,
69
+ capture_output=True,
70
+ timeout=60,
71
+ ).stdout
72
+
73
+ run("read-tree", f"{base_commit}^{{tree}}")
74
+ # All filter drivers are undefined in the private configuration. The
75
+ # workspace's clean filters, fsmonitor and hooks cannot be invoked.
76
+ run("add", "--all", "--", ".")
77
+ return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
78
+
79
+
80
+ def main(argv: list[str] | None = None) -> int:
81
+ parser = argparse.ArgumentParser(description=__doc__)
82
+ parser.add_argument("workspace", type=Path)
83
+ parser.add_argument("base_commit")
84
+ args = parser.parse_args(argv)
85
+ try:
86
+ patch = capture(args.workspace, args.base_commit)
87
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
88
+ # Do not echo child stderr: it may contain workspace-controlled data.
89
+ sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n")
90
+ return 1
91
+ sys.stdout.buffer.write(patch)
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
tasks/livewire__livewire-10629/tests/instruction.md ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** [4.x] Fix wire transition skipped after flux toast auto-dismissed
4
+
5
+ ## Description
6
+
7
+ ### Problem
8
+
9
+ `wire:transition` currently skips a View Transition whenever there is an open modal dialog or popover:
10
+
11
+ ```js
12
+ if (document.querySelector('dialog:modal, :popover-open')) {
13
+ return callback()
14
+ }
15
+ ```
16
+
17
+ This is necessary for open popovers because View Transition pseudo-elements can paint above the top layer. Starting a transition while a popover is open can cause the transition to render over the popover.
18
+
19
+ However, `:popover-open` only tells us that the popover itself is open. It does not tell us whether the popover currently has any **visible UI**.
20
+
21
+ Some components keep a popover open as a persistent container while its contents are hidden. In that case, `:popover-open` still matches even though there is nothing visible that needs to be protected from the View Transition.
22
+
23
+ This causes subsequent Livewire transitions to be skipped unnecessarily.
24
+
25
+ ### Solution
26
+
27
+ Keep the existing behavior for modal dialogs, but for popovers only skip the transition when the popover contains a visible element:
28
+
29
+ ```js
30
+ if (document.querySelector('dialog:modal')) return callback()
31
+
32
+ for (let popover of document.querySelectorAll(':popover-open')) {
33
+ for (let el of popover.querySelectorAll('*')) {
34
+ if (el.checkVisibility()) return callback()
35
+ }
36
+ }
37
+ ```
38
+
39
+ `checkVisibility()` lets us determine whether the open popover actually contains visible UI without relying on any framework- or component-specific selectors.
40
+
41
+ This keeps the behavior generic and avoids coupling Livewire's transition implementation to a particular component library or DOM structure.
42
+
43
+ ### Why not just check `:popover-open`?
44
+
45
+ An open popover can remain mounted and open while its contents are hidden. Treating every `:popover-open` element as blocking would therefore incorrectly skip transitions when there is no visible popover.
46
+
47
+ At the same time, removing the `:popover-open` check entirely would reintroduce the issue where an actually visible popover can be covered by View Transition pseudo-elements.
48
+
49
+ The new check handles both cases:
50
+
51
+ * **Visible popover** → skip the transition.
52
+ * **Open but visually inactive popover** → allow the transition.
53
+ * **Modal dialog** → skip the transition as before.
54
+
55
+ ### Why `checkVisibility()`?
56
+
57
+ Checking text content, child count, or specific element names would be unreliable:
58
+
59
+ * A popover can contain non-textual UI.
60
+ * A popover can contain DOM nodes that are hidden.
61
+ * Empty/non-empty DOM structure does not necessarily correspond to visible UI.
62
+ * Component-specific selectors would couple Livewire to another package's implementation details.
63
+
64
+ `checkVisibility()` directly answers the relevant question: whether there is currently a visible element inside the open popover.
65
+
66
+ Fixes:
67
+
68
+ ## Task
69
+
70
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `db3f789c8fa5`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/livewire__livewire-10629/tests/oracle.patch ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/js/directives/wire-transition.js b/js/directives/wire-transition.js
2
+ index fc61399d..3cf56e58 100644
3
+ --- a/js/directives/wire-transition.js
4
+ +++ b/js/directives/wire-transition.js
5
+ @@ -44,7 +44,18 @@ export async function transitionDomMutation(fromEl, toEl, callback, options = {}
6
+ // Skip entirely if a top-layer element is already open (transitions behind
7
+ // it are invisible to the user and the ::view-transition pseudo-elements
8
+ // would paint above it during animation)...
9
+ - if (document.querySelector('dialog:modal, :popover-open')) return callback()
10
+ + if (document.querySelector('dialog:modal')) return callback()
11
+ +
12
+ + // An open popover only blocks the transition if it has visible descendants.
13
+ + // Some components (e.g. toast hosts) keep an empty popover open as a
14
+ + // persistent container — the host element itself always passes
15
+ + // checkVisibility() while open, so visible *descendants* are the proxy
16
+ + // for "this popover is actually showing UI"...
17
+ + for (let popover of document.querySelectorAll(':popover-open')) {
18
+ + for (let el of popover.querySelectorAll('*')) {
19
+ + if (el.checkVisibility()) return callback()
20
+ + }
21
+ + }
22
+
23
+ // Set transition names right before the transition starts (not permanently)...
24
+ setTransitionNames(fromEl, options)
25
+ diff --git a/src/Features/SupportTransitions/BrowserTest.php b/src/Features/SupportTransitions/BrowserTest.php
26
+ index 0622e9db..f6f50daa 100644
27
+ --- a/src/Features/SupportTransitions/BrowserTest.php
28
+ +++ b/src/Features/SupportTransitions/BrowserTest.php
29
+ @@ -500,4 +500,92 @@ class BrowserTest extends \Tests\BrowserTestCase
30
+ ->waitUntil("!$animationsRunning")
31
+ ;
32
+ }
33
+ +
34
+ + public function test_transition_runs_when_popover_stays_open_without_visible_content()
35
+ + {
36
+ + Livewire::visit(
37
+ + new class extends \Livewire\Component {
38
+ + public $show = false;
39
+ +
40
+ + public function toggle()
41
+ + {
42
+ + $this->show = ! $this->show;
43
+ + }
44
+ +
45
+ + public function render()
46
+ + {
47
+ + return <<<'HTML'
48
+ + <div>
49
+ + <button wire:click="toggle" dusk="toggle">Toggle</button>
50
+ +
51
+ + @if ($show)
52
+ + <div wire:transition dusk="target">Hello</div>
53
+ + @endif
54
+ +
55
+ + <div popover="manual" dusk="toast-host" x-init="$el.showPopover()">
56
+ + <template>
57
+ + <div>Hidden popover content</div>
58
+ + </template>
59
+ + </div>
60
+ + </div>
61
+ + HTML;
62
+ + }
63
+ + }
64
+ + )
65
+ + ->waitUntil("document.querySelector('[dusk=toast-host]').matches(':popover-open')")
66
+ + ->tap(fn ($browser) => $browser->script("
67
+ + window.__startViewTransitionCalled = false
68
+ + let original = document.startViewTransition.bind(document)
69
+ + document.startViewTransition = function (...args) {
70
+ + window.__startViewTransitionCalled = true
71
+ + return original(...args)
72
+ + }
73
+ + "))
74
+ + ->waitForLivewire()->click('@toggle')
75
+ + ->waitFor('@target')
76
+ + ->assertScript('window.__startViewTransitionCalled', true);
77
+ + }
78
+ +
79
+ + public function test_transition_does_not_run_when_popover_has_visible_content()
80
+ + {
81
+ + Livewire::visit(
82
+ + new class extends \Livewire\Component {
83
+ + public $show = false;
84
+ +
85
+ + public function toggle()
86
+ + {
87
+ + $this->show = ! $this->show;
88
+ + }
89
+ +
90
+ + public function render()
91
+ + {
92
+ + return <<<'HTML'
93
+ + <div>
94
+ + <button wire:click="toggle" dusk="toggle">Toggle</button>
95
+ +
96
+ + @if ($show)
97
+ + <div wire:transition dusk="target">Hello</div>
98
+ + @endif
99
+ +
100
+ + <div popover="manual" dusk="toast-host" x-init="$el.showPopover()">
101
+ + <div>Visible popover content</div>
102
+ + </div>
103
+ + </div>
104
+ + HTML;
105
+ + }
106
+ + }
107
+ + )
108
+ + ->waitUntil("document.querySelector('[dusk=toast-host]').matches(':popover-open')")
109
+ + ->tap(fn ($browser) => $browser->script("
110
+ + window.__startViewTransitionCalled = false
111
+ + let original = document.startViewTransition.bind(document)
112
+ + document.startViewTransition = function (...args) {
113
+ + window.__startViewTransitionCalled = true
114
+ + return original(...args)
115
+ + }
116
+ + "))
117
+ + ->waitForLivewire()->click('@toggle')
118
+ + ->waitFor('@target')
119
+ + ->assertScript('window.__startViewTransitionCalled', false);
120
+ + }
121
+ }
tasks/livewire__livewire-10629/tests/test.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uxo pipefail
3
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
4
+ cd /workspace
5
+ mkdir -p /logs/verifier
6
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json
7
+ CAPTURE_DIR="$(mktemp -d)" || exit 1
8
+ trap 'rm -rf -- "$CAPTURE_DIR"' EXIT
9
+ if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace db3f789c8fa5ed49a7e1a785e6b0355d6304ec95 > "$CAPTURE_DIR/predicted.patch"; then
10
+ echo "0.0" > /logs/verifier/reward.txt
11
+ printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json
12
+ exit 0
13
+ fi
14
+ rm -f /logs/verifier/predicted.patch
15
+ cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch
16
+ : 'START_VERIFY_OUTPUT'
17
+ if ! python3 -I "$SCRIPT_DIR/verifier.py" \
18
+ "$SCRIPT_DIR/oracle.patch" \
19
+ "$CAPTURE_DIR/predicted.patch" \
20
+ "$SCRIPT_DIR/instruction.md"; then
21
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json
22
+ printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json
23
+ fi
24
+ : 'END_VERIFY_OUTPUT'
25
+ exit 0
tasks/livewire__livewire-10629/tests/verifier.py ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """In-container verifier for pr_diff tasks (6-component reward).
2
+
3
+ This module is the **standalone verifier** that runs inside the task's
4
+ Docker container, NOT a helper used at generation time. Generation emits
5
+ its source as ``tests/verifier.py``. Harbor delivers it at verify time,
6
+ and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
7
+
8
+ Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
9
+
10
+ format_valid (0 or 1) — predicted parses as a unified diff (guard)
11
+ size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...)
12
+ catches "rampage through the codebase"
13
+ file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard —
14
+ symmetric penalty over-punishes extras)
15
+ region_overlap ([0, 1]) — predicted hunks overlap oracle hunks
16
+ (strongest spatial-localization signal)
17
+ similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only
18
+ (no free credit for context lines)
19
+ llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?"
20
+ Anthropic Haiku by default; any OpenAI-
21
+ compatible server via ``R2E_JUDGE_ENDPOINT``.
22
+ null when the judge is unavailable
23
+ (no key or model, network, unreadable
24
+ reply) → ungraded, no reward file; a
25
+ reply without a valid score (refusal,
26
+ content filter, empty, no "score") → a
27
+ graded 0
28
+
29
+ Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from
30
+ the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task
31
+ pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).
32
+ Override per-task via ``task.toml.metadata`` or per-run via env vars
33
+ ``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /
34
+ ``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they
35
+ reach the verifier container).
36
+
37
+ Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model
38
+ (default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible
39
+ server (vLLM, Ollama, a gateway) and switches the request to
40
+ ``<endpoint>/chat/completions`` with a bearer token from
41
+ ``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted
42
+ servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default
43
+ route and is never sent to a custom endpoint.
44
+
45
+ Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40
46
+ when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a
47
+ charitable judge from inflating scores on wildly wrong-sized patches).
48
+
49
+ Outputs (mirrors `_pr_runtime_verifier.py` after #75):
50
+ /logs/verifier/reward.txt — single float (Harbor reads this);
51
+ graded runs only
52
+ /logs/verifier/reward-details.json — full component breakdown + status
53
+ (structured diagnostics; Harbor's `reward.json` schema is flat-numeric-
54
+ only, so the breakdown goes to the `reward-details.json` sidecar which
55
+ Harbor renders under Verifier Logs → Rewards)
56
+
57
+ Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,
58
+ ``urllib``, ``sys``. The same module is imported by the unit tests
59
+ under ``tests/test_pr_diff_verifier.py`` so the in-container behavior
60
+ stays in lockstep with what we test.
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import argparse
66
+ import difflib
67
+ import json
68
+ import math
69
+ import os
70
+ import re
71
+ import sys
72
+ import urllib.error
73
+ import urllib.request
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Parsing helpers (shared by multiple components)
77
+ # ---------------------------------------------------------------------------
78
+
79
+ _DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")
80
+ _HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
81
+ _FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")
82
+ _INDEX_RE = re.compile(r"^index ")
83
+
84
+
85
+ def file_paths(diff: str) -> set[str]:
86
+ """Return the set of ``b/<path>`` paths touched by a unified diff."""
87
+ paths: set[str] = set()
88
+ for line in diff.splitlines():
89
+ m = _DIFF_HEADER_RE.match(line)
90
+ if m:
91
+ paths.add(m.group(2))
92
+ return paths
93
+
94
+
95
+ def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]:
96
+ """For each touched file, return list of (start_line, end_line) ranges
97
+ on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``).
98
+ """
99
+ out: dict[str, list[tuple[int, int]]] = {}
100
+ current_file: str | None = None
101
+ for line in diff.splitlines():
102
+ m = _DIFF_HEADER_RE.match(line)
103
+ if m:
104
+ current_file = m.group(2)
105
+ out.setdefault(current_file, [])
106
+ continue
107
+ m = _HUNK_HEADER_RE.match(line)
108
+ if m and current_file is not None:
109
+ new_start = int(m.group(3))
110
+ new_count = int(m.group(4) or "1")
111
+ end = new_start + max(new_count - 1, 0)
112
+ out[current_file].append((new_start, end))
113
+ return out
114
+
115
+
116
+ def _normalize_changes_only(diff: str) -> list[str]:
117
+ """Return the +/- lines (the actual changes) for similarity scoring.
118
+
119
+ Drops:
120
+ - ``diff --git`` / ``index abc..def`` metadata
121
+ - ``@@ ... @@`` hunk markers (volatile line numbers)
122
+ - context lines (no +/- prefix) — these are unchanged code, scoring
123
+ them inflates similarity for trivial patches
124
+ Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity
125
+ stays in the comparison; normalizes off the tab+timestamp suffix git
126
+ sometimes appends.
127
+ """
128
+ out: list[str] = []
129
+ for line in diff.splitlines():
130
+ if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line):
131
+ continue
132
+ if _HUNK_HEADER_RE.match(line):
133
+ continue
134
+ if _FILE_MARKER_RE.match(line):
135
+ out.append(line.split("\t")[0].strip())
136
+ continue
137
+ # +/- lines (actual changes)
138
+ if line.startswith("+") or line.startswith("-"):
139
+ out.append(line)
140
+ return out
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Reward components
145
+ # ---------------------------------------------------------------------------
146
+
147
+
148
+ def format_valid(predicted: str) -> float:
149
+ """1.0 if the predicted text looks like a unified diff; else 0.0.
150
+
151
+ Requires both a ``diff --git`` header and at least one real +/- line
152
+ (not the ``---`` / ``+++`` file-marker lines).
153
+ """
154
+ if not predicted.strip():
155
+ return 0.0
156
+ has_header = False
157
+ has_change = False
158
+ for line in predicted.splitlines():
159
+ if _DIFF_HEADER_RE.match(line):
160
+ has_header = True
161
+ elif (line.startswith("+") or line.startswith("-")) and not line.startswith(
162
+ ("+++ ", "--- ")
163
+ ):
164
+ has_change = True
165
+ if has_header and has_change:
166
+ return 1.0
167
+ return 0.0
168
+
169
+
170
+ def file_targeting(oracle: str, predicted: str) -> float:
171
+ """F1 over the changed-file sets.
172
+
173
+ Why F1 instead of Jaccard:
174
+ - Missing an oracle file (FN) is a *big* failure.
175
+ - Touching one unrelated extra file (FP) is a small one.
176
+ - Jaccard punishes both equally, which over-penalizes the agent
177
+ for any extra exploration.
178
+ - F1 weights TP twice, giving partial credit when the agent finds
179
+ most-but-not-all of the oracle files even with some noise.
180
+
181
+ Returns 1.0 if both sides touch zero files (degenerate).
182
+ """
183
+ o = file_paths(oracle)
184
+ p = file_paths(predicted)
185
+ if not o and not p:
186
+ return 1.0
187
+ tp = len(o & p)
188
+ fn = len(o - p)
189
+ fp = len(p - o)
190
+ if tp == 0:
191
+ return 0.0
192
+ # F1 = 2·TP / (2·TP + FN + FP)
193
+ return (2 * tp) / (2 * tp + fn + fp)
194
+
195
+
196
+ def _count_loc_changes(diff: str) -> int:
197
+ """Number of real +/- lines (excluding file-marker lines)."""
198
+ n = 0
199
+ for line in diff.splitlines():
200
+ if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")):
201
+ n += 1
202
+ return n
203
+
204
+
205
+ def size_sanity(oracle: str, predicted: str) -> float:
206
+ """Penalize predicted patches that are wildly larger / smaller than the oracle.
207
+
208
+ Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``.
209
+ Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
210
+
211
+ This is the "don't rampage through the codebase" guard — a 200-line
212
+ diff for a 3-line oracle scores ~0.015 here even if every other
213
+ component looks OK.
214
+ """
215
+ o_loc = _count_loc_changes(oracle)
216
+ p_loc = _count_loc_changes(predicted)
217
+ if o_loc == 0 and p_loc == 0:
218
+ return 1.0
219
+ if o_loc == 0 or p_loc == 0:
220
+ return 0.0
221
+ return min(o_loc, p_loc) / max(o_loc, p_loc)
222
+
223
+
224
+ def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float:
225
+ """For each oracle hunk, did the predicted diff edit a line within
226
+ ``slack_lines`` of that hunk in the same file?
227
+
228
+ Returns the fraction of oracle hunks that have at least one matching
229
+ predicted hunk. ``slack_lines`` tolerates slight line-number drift
230
+ when git diff renders the predicted hunk at a different offset.
231
+ """
232
+ o_ranges = hunk_ranges(oracle)
233
+ p_ranges = hunk_ranges(predicted)
234
+ total = sum(len(v) for v in o_ranges.values())
235
+ if total == 0:
236
+ return 1.0 # oracle has no hunks (degenerate)
237
+ matched = 0
238
+ for fname, ranges in o_ranges.items():
239
+ p_in_file = p_ranges.get(fname, [])
240
+ for o_start, o_end in ranges:
241
+ for p_start, p_end in p_in_file:
242
+ # Interval overlap with slack — max(starts) <= min(ends) + slack
243
+ if max(o_start, p_start) <= min(o_end, p_end) + slack_lines:
244
+ matched += 1
245
+ break
246
+ return matched / total
247
+
248
+
249
+ def similarity(oracle: str, predicted: str) -> float:
250
+ """SequenceMatcher ratio over +/- lines only.
251
+
252
+ No free credit for context lines — fixes the v0.8.1 inflation where a
253
+ one-line fix scored ~0.7 just because the 3 context lines on either
254
+ side were "matched".
255
+ """
256
+ if not predicted.strip():
257
+ return 0.0
258
+ o = _normalize_changes_only(oracle)
259
+ p = _normalize_changes_only(predicted)
260
+ if not o:
261
+ return 0.0
262
+ # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000
263
+ # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can
264
+ # run the verifier past Harbor's timeout. Above this many line pairs,
265
+ # fall back to difflib's popular-element heuristic, which stays fast.
266
+ exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS
267
+ return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
268
+
269
+
270
+ _SIMILARITY_EXACT_PAIRS = 400_000
271
+
272
+ # A predicted patch over 10x the oracle's changed lines is already a
273
+ # catastrophic size mismatch (size_sanity < 0.10). Past this floor such a
274
+ # patch is a graded 0 instead of being scored, so one huge file can't slow
275
+ # the verifier past its timeout and turn a failing episode into a dropped,
276
+ # ungraded one. The byte cap stops it from being read at all.
277
+ _MAX_PREDICTED_FACTOR = 10
278
+ _MAX_PREDICTED_FLOOR_LOC = 1_000
279
+ _MAX_PREDICTED_BYTES = 16 * 1024 * 1024
280
+
281
+
282
+ def predicted_too_large(oracle: str, predicted: str) -> bool:
283
+ """Whether the predicted patch is too large to score (a graded 0)."""
284
+ limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC)
285
+ return _count_loc_changes(predicted) > limit
286
+
287
+
288
+ # ---------------------------------------------------------------------------
289
+ # LLM-as-judge (Anthropic Messages API, stdlib urllib)
290
+ # ---------------------------------------------------------------------------
291
+
292
+
293
+ _JUDGE_PROMPT = (
294
+ "You are scoring a code-fix patch on whether it logically addresses the "
295
+ "described issue. Output a single JSON object: "
296
+ '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n'
297
+ "DO NOT use the oracle to grade. Score on:\n"
298
+ " - Does the predicted diff touch code regions that could plausibly fix the issue?\n"
299
+ " - Is the change direction consistent with what the issue describes?\n"
300
+ " - Is it a real attempt (not boilerplate, not no-op)?\n\n"
301
+ "Issue:\n{instruction}\n\n"
302
+ "Oracle (reference fix for comparison only — don't grade on similarity to it):\n"
303
+ "{oracle}\n\n"
304
+ "Predicted:\n{predicted}\n\n"
305
+ "Return ONLY the JSON object."
306
+ )
307
+
308
+
309
+ _DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"
310
+ _ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"
311
+ # Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /
312
+ # Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses.
313
+ _PLACEHOLDER_API_KEY = "EMPTY"
314
+
315
+
316
+ def llm_judge(
317
+ *,
318
+ instruction: str,
319
+ oracle: str,
320
+ predicted: str,
321
+ api_key: str,
322
+ model: str = _DEFAULT_JUDGE_MODEL,
323
+ timeout: int = 60,
324
+ endpoint: str | None = None,
325
+ ) -> tuple[float | None, str]:
326
+ """Return ``(score, status)``.
327
+
328
+ ``score`` is a float in [0, 1] on success, ``None`` on failure.
329
+ ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` /
330
+ ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` /
331
+ ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``.
332
+ ``output_limit`` means the judge exhausted its configured token budget
333
+ (ungraded, even if a partial answer contains a score). ``parse`` means
334
+ the provider's body isn't JSON or has the wrong shape (ungraded); a reply
335
+ with no usable text (refusal, content filter, empty) or no valid score is
336
+ ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never
337
+ increases the other weights.
338
+
339
+ ``endpoint`` — base URL of an OpenAI-compatible server. When set, the
340
+ request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a
341
+ bearer token, at temperature 0, and ``model`` must be given explicitly;
342
+ otherwise it goes to Anthropic's Messages API unchanged.
343
+ """
344
+ if not api_key:
345
+ return None, "no_api_key"
346
+ if endpoint and not model:
347
+ return None, "no_judge_model"
348
+ if not predicted.strip():
349
+ return 0.0, "empty_predicted"
350
+
351
+ # Truncate hard so we don't blow up the prompt for big diffs
352
+ prompt = _JUDGE_PROMPT.format(
353
+ instruction=instruction[:4000],
354
+ oracle=oracle[:4000],
355
+ predicted=predicted[:4000],
356
+ )
357
+ payload: dict = {
358
+ "model": model,
359
+ "max_tokens": 200,
360
+ "messages": [{"role": "user", "content": prompt}],
361
+ }
362
+ if endpoint:
363
+ # Small self-hosted models are noisy judges at their default sampling
364
+ # temperature (same input scoring 0.0 one call and 1.0 the next); pin
365
+ # them to greedy. The Anthropic route keeps its defaults — the weights
366
+ # were calibrated against them.
367
+ payload["temperature"] = 0
368
+ url = endpoint.rstrip("/") + "/chat/completions"
369
+ headers = {
370
+ "authorization": f"Bearer {api_key}",
371
+ "content-type": "application/json",
372
+ }
373
+ else:
374
+ url = _ANTHROPIC_MESSAGES_URL
375
+ headers = {
376
+ "x-api-key": api_key,
377
+ "anthropic-version": "2023-06-01",
378
+ "content-type": "application/json",
379
+ }
380
+ body = json.dumps(payload).encode("utf-8")
381
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
382
+ try:
383
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
384
+ raw = resp.read().decode("utf-8")
385
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError):
386
+ return None, "network"
387
+
388
+ try:
389
+ response = json.loads(raw)
390
+ except json.JSONDecodeError:
391
+ return None, "parse"
392
+ # Provider-reported truncation is a grader capacity failure, not evidence
393
+ # that the submitted patch is wrong. Reasoning models can spend the entire
394
+ # output budget before producing visible text. Never grade a partial score.
395
+ if isinstance(response, dict):
396
+ choices = response.get("choices")
397
+ if endpoint:
398
+ if (
399
+ isinstance(choices, list)
400
+ and choices
401
+ and isinstance(choices[0], dict)
402
+ and choices[0].get("finish_reason") == "length"
403
+ ):
404
+ return None, "output_limit"
405
+ elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}:
406
+ return None, "output_limit"
407
+ text = _judge_text(response, openai_compatible=bool(endpoint))
408
+ if text is None:
409
+ return None, "parse"
410
+
411
+ # Pull the first JSON object out of the model's response
412
+ m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL)
413
+ if not m:
414
+ return None, "missing_score"
415
+ try:
416
+ obj = json.loads(m.group(0))
417
+ score = obj.get("score")
418
+ except (json.JSONDecodeError, ValueError, TypeError):
419
+ return None, "missing_score"
420
+ if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score):
421
+ return None, "invalid_score"
422
+ return float(score), "ok"
423
+
424
+
425
+ def _judge_text(payload: object, *, openai_compatible: bool) -> str | None:
426
+ """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
427
+
428
+ A refusal or a content filter is a well-formed reply with no usable text.
429
+ The agent's patch is in the prompt, so it can provoke one: that is ``""``,
430
+ which grades 0, not ``None``, which leaves the run ungraded.
431
+
432
+ Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and
433
+ ``content`` empty or holding partial text to discard. OpenAI-compatible:
434
+ ``message.content`` is null with a ``refusal`` string or
435
+ ``finish_reason: "content_filter"``.
436
+ """
437
+ if not isinstance(payload, dict):
438
+ return None
439
+ if openai_compatible:
440
+ choices = payload.get("choices")
441
+ if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
442
+ return None
443
+ message = choices[0].get("message")
444
+ if not isinstance(message, dict):
445
+ return None
446
+ if message.get("refusal") or choices[0].get("finish_reason") == "content_filter":
447
+ return ""
448
+ content = message.get("content")
449
+ if content is None:
450
+ return ""
451
+ if isinstance(content, str):
452
+ return content
453
+ if isinstance(content, list): # content parts
454
+ return "".join(
455
+ part.get("text", "")
456
+ for part in content
457
+ if isinstance(part, dict) and isinstance(part.get("text", ""), str)
458
+ )
459
+ return None
460
+ content = payload.get("content")
461
+ if not isinstance(content, list):
462
+ return None
463
+ if payload.get("stop_reason") == "refusal":
464
+ return ""
465
+ return "".join(
466
+ block["text"]
467
+ for block in content
468
+ if isinstance(block, dict)
469
+ and block.get("type", "text") == "text"
470
+ and isinstance(block.get("text"), str)
471
+ )
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # Combination
476
+ # ---------------------------------------------------------------------------
477
+
478
+
479
+ # Judge replies the agent can provoke: its patch text is part of the judge
480
+ # prompt, so it can steer the answer away from a valid score. These are a
481
+ # graded 0. An unreadable provider envelope (`parse`), missing configuration,
482
+ # a disabled judge, transport errors and an exhausted judge output budget leave
483
+ # the evaluation ungraded. Truncation alone cannot establish an incorrect patch.
484
+ _JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
485
+
486
+
487
+ def evaluation_status(judge_score: float | None, judge_status: str) -> str:
488
+ """`graded` when the judge scored or the agent can have caused its failure."""
489
+ if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO:
490
+ return "graded"
491
+ return "ungraded"
492
+
493
+
494
+ def combine(components: dict[str, float | None], weights: dict[str, float]) -> float:
495
+ """Combine declared components, requiring a positively weighted judge.
496
+
497
+ Without a judge score the result is 0. ``main`` records it as a graded 0
498
+ when the agent can have caused the judge failure, and otherwise writes no
499
+ reward file, so Harbor reports the trial as VERIFIER_FAILED.
500
+ """
501
+ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None:
502
+ return 0.0
503
+ if any(w > 0 and components.get(k) is None for k, w in weights.items()):
504
+ return 0.0
505
+ return _weighted_mean(components, weights)
506
+
507
+
508
+ def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float:
509
+ available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None]
510
+ if not available:
511
+ return 0.0
512
+ # Relative weights need not sum to one. Scale first so large finite
513
+ # overrides cannot overflow the numerator or denominator into NaN.
514
+ scale = max(w for _, w in available)
515
+ normalized = [(k, w / scale) for k, w in available]
516
+ return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
517
+
518
+
519
+ # ---------------------------------------------------------------------------
520
+ # Entry point (invoked by tests/test.sh inside the container)
521
+ # ---------------------------------------------------------------------------
522
+
523
+
524
+ # Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer
525
+ # analysis grounded in per-task component data):
526
+ #
527
+ # - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero
528
+ # discriminative signal — its 0.05 weight was pure dead weight.
529
+ # - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.
530
+ # Carrying both at 0.20 double-counts positional accuracy and
531
+ # additionally penalizes legitimate alternative implementations.
532
+ # - llm_judge → 0.50: only component capturing semantic correctness
533
+ # independent of textual form; diverges informatively from
534
+ # similarity on cases like tokenizers (judge=0.72, sim=0.08).
535
+ # - region_overlap stays 0.20: strongest spatial-localization signal.
536
+ # - file_targeting → 0.12: leading indicator, less correlated with the
537
+ # rest than region/similarity are with each other.
538
+ # - size_sanity → 0.08: useful outlier detector for catastrophic
539
+ # over/under-generation (prettier=0.01, serde=0.08).
540
+ #
541
+ # Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00.
542
+ _DEFAULT_WEIGHTS = {
543
+ "format_valid": 0.00,
544
+ "size_sanity": 0.08,
545
+ "file_targeting": 0.12,
546
+ "region_overlap": 0.20,
547
+ "similarity": 0.10,
548
+ "llm_judge": 0.50,
549
+ }
550
+
551
+ # Hard cap: when size_sanity < this threshold, clamp final reward to
552
+ # ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating
553
+ # the score on patches that are wildly the wrong size (catastrophic
554
+ # over- or under-generation).
555
+ _CATASTROPHIC_SIZE_THRESHOLD = 0.10
556
+ _CATASTROPHIC_SIZE_CAP = 0.40
557
+
558
+
559
+ def _read_weights_from_env() -> dict[str, float]:
560
+ """Override defaults via R2E_W_* env vars (set in container by harbor)."""
561
+ overrides = {
562
+ "format_valid": os.environ.get("R2E_W_FORMAT"),
563
+ "size_sanity": os.environ.get("R2E_W_SIZE"),
564
+ "file_targeting": os.environ.get("R2E_W_FILE"),
565
+ "region_overlap": os.environ.get("R2E_W_REGION"),
566
+ "similarity": os.environ.get("R2E_W_SIM"),
567
+ "llm_judge": os.environ.get("R2E_W_JUDGE"),
568
+ }
569
+ out = dict(_DEFAULT_WEIGHTS)
570
+ for k, v in overrides.items():
571
+ if v is None:
572
+ continue
573
+ try:
574
+ value = float(v)
575
+ if math.isfinite(value) and value >= 0:
576
+ out[k] = value
577
+ except (TypeError, ValueError):
578
+ continue
579
+ return out
580
+
581
+
582
+ def _judge_config_from_env() -> tuple[str, str, str | None]:
583
+ """``(api_key, model, endpoint)`` for the judge, from the verifier env.
584
+
585
+ With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY``
586
+ (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to
587
+ the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a
588
+ self-hosted server won't have Haiku): when unset, ``model`` comes back
589
+ as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of
590
+ calling out. Without an endpoint the default Anthropic route is
591
+ unchanged.
592
+ """
593
+ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None
594
+ model = os.environ.get("R2E_JUDGE_MODEL", "").strip()
595
+ if endpoint:
596
+ api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY
597
+ return api_key, model, endpoint
598
+ return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
599
+
600
+
601
+ def main(argv: list[str] | None = None) -> int:
602
+ parser = argparse.ArgumentParser(description=__doc__)
603
+ parser.add_argument("oracle")
604
+ parser.add_argument("predicted")
605
+ parser.add_argument("instruction")
606
+ parser.add_argument("--out-dir", default="/logs/verifier")
607
+ args = parser.parse_args(argv)
608
+ os.makedirs(args.out_dir, exist_ok=True)
609
+ # This run is the only authority on the reward: an earlier or planted
610
+ # reward file must not stand if this evaluation ends up ungraded.
611
+ for name in ("reward.txt", "reward.json"):
612
+ try:
613
+ os.unlink(os.path.join(args.out_dir, name))
614
+ except FileNotFoundError:
615
+ pass
616
+ oracle = _read_or_empty(args.oracle)
617
+ try:
618
+ oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES
619
+ except OSError:
620
+ oversized = False
621
+ predicted = "" if oversized else _read_or_empty(args.predicted)
622
+ if oversized or predicted_too_large(oracle, predicted):
623
+ breakdown = {
624
+ "final_reward": 0.0,
625
+ "evaluation_status": "graded",
626
+ "eval_trustworthy": False,
627
+ "predicted_status": "predicted_too_large",
628
+ }
629
+ _write_outputs(args.out_dir, 0.0, breakdown)
630
+ return 0
631
+ instruction = _read_or_empty(args.instruction)
632
+ api_key, judge_model, judge_endpoint = _judge_config_from_env()
633
+
634
+ fv = format_valid(predicted)
635
+ ss = size_sanity(oracle, predicted)
636
+ ft = file_targeting(oracle, predicted)
637
+ ro = region_overlap(oracle, predicted)
638
+ sim = similarity(oracle, predicted)
639
+ weights = _read_weights_from_env()
640
+ if weights["llm_judge"] <= 0:
641
+ judge_score, judge_status = None, "disabled"
642
+ else:
643
+ judge_score, judge_status = llm_judge(
644
+ instruction=instruction,
645
+ oracle=oracle,
646
+ predicted=predicted,
647
+ api_key=api_key,
648
+ model=judge_model,
649
+ endpoint=judge_endpoint,
650
+ )
651
+
652
+ components: dict[str, float | None] = {
653
+ "format_valid": fv,
654
+ "size_sanity": ss,
655
+ "file_targeting": ft,
656
+ "region_overlap": ro,
657
+ "similarity": sim,
658
+ "llm_judge": judge_score,
659
+ }
660
+ final = combine(components, weights)
661
+ final = max(0.0, min(1.0, final))
662
+
663
+ # Hard cap on catastrophic size mismatches. Without this, a charitable
664
+ # judge can inflate the reward on patches that are dramatically the
665
+ # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge
666
+ # was lenient at 0.25 despite the patch being a near-no-op vs a
667
+ # 500-line oracle). The cap kicks in only at the extremes.
668
+ if ss < _CATASTROPHIC_SIZE_THRESHOLD:
669
+ final = min(final, _CATASTROPHIC_SIZE_CAP)
670
+
671
+ status = evaluation_status(judge_score, judge_status)
672
+ breakdown = {
673
+ # No reward exists for an ungraded evaluation: null, not a placeholder 0.
674
+ "final_reward": round(final, 6) if status == "graded" else None,
675
+ "evaluation_status": status,
676
+ "eval_trustworthy": judge_score is not None,
677
+ "diagnostic_similarity": round(
678
+ _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}),
679
+ 6,
680
+ ),
681
+ "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()},
682
+ "weights": {k: round(v, 6) for k, v in weights.items()},
683
+ "judge_model": judge_model if judge_status == "ok" else None,
684
+ "judge_endpoint": judge_endpoint,
685
+ "judge_status": judge_status,
686
+ }
687
+
688
+ _write_outputs(args.out_dir, final, breakdown)
689
+ return 0
690
+
691
+
692
+ def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None:
693
+ # An ungraded evaluation writes no reward file. Harbor then raises
694
+ # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is
695
+ # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout
696
+ # instead of training on a 0. Harbor's job mean and pass@k still count the
697
+ # trial as 0, so evaluation stays fail-closed.
698
+ if breakdown["evaluation_status"] == "graded":
699
+ with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f:
700
+ f.write(f"{final:.6f}\n")
701
+ # Harbor's `reward.json` must be a flat map of floats/ints (spec, see
702
+ # <https://harborframework.com/docs/tasks>); our breakdown carries nested
703
+ # dicts, judge strings, and status strings, so it goes to the sidecar the
704
+ # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig)
705
+ # for `_pr_runtime_verifier.py`.
706
+ with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f:
707
+ json.dump(breakdown, f, indent=2)
708
+
709
+ # Also print to stdout so harbor's log captures the breakdown
710
+ print(json.dumps(breakdown, indent=2))
711
+
712
+
713
+ def _read_or_empty(path: str) -> str:
714
+ try:
715
+ with open(path, encoding="utf-8") as f:
716
+ return f.read()
717
+ except (OSError, UnicodeDecodeError):
718
+ return ""
719
+
720
+
721
+ if __name__ == "__main__":
722
+ sys.exit(main())
723
+
724
+
725
+ __all__ = [
726
+ "combine",
727
+ "file_paths",
728
+ "file_targeting",
729
+ "format_valid",
730
+ "hunk_ranges",
731
+ "llm_judge",
732
+ "main",
733
+ "predicted_too_large",
734
+ "region_overlap",
735
+ "similarity",
736
+ "size_sanity",
737
+ ]
tasks/livewire__livewire-10630/environment/Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.
2
+ # Agent-agnostic: the agent (claude-code / openhands / codex / etc.)
3
+ # installs itself at run time via its harbor adapter. We only ship
4
+ # the source repo — the oracle + verifier arrive at verify time via
5
+ # tests/, never baked into the agent's image.
6
+ FROM python:3.12-slim
7
+ ARG GITHUB_TOKEN=
8
+ RUN apt-get update \
9
+ && apt-get install -y --no-install-recommends git ca-certificates curl \
10
+ && rm -rf /var/lib/apt/lists/*
11
+ RUN git config --global --add safe.directory /workspace \
12
+ && git config --global init.defaultBranch main \
13
+ && git config --global advice.detachedHead false
14
+ RUN if [ -n "$GITHUB_TOKEN" ]; then \
15
+ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin 16c5b608ab422f8135e16e5cc1e0af3c72d3d1cc 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard 16c5b608ab422f8135e16e5cc1e0af3c72d3d1cc \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base 16c5b608ab422f8135e16e5cc1e0af3c72d3d1cc \
26
+ && git remote remove origin 2>/dev/null || true
27
+ RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \
28
+ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \
29
+ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \
30
+ && git reflog expire --expire=now --all 2>/dev/null || true \
31
+ && git gc --prune=now 2>/dev/null || true
32
+ RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \
33
+ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \
34
+ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \
35
+ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \
36
+ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \
37
+ fi
tasks/livewire__livewire-10630/instruction.md ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** [4.x] Add a trusted-storage codec for synthesized values
4
+
5
+ ## Description
6
+
7
+ ## Why
8
+
9
+ Features that persist Livewire property values outside the normal browser snapshot need the synth system, but should not each learn about `ComponentContext`, recursive synth tuples, collision-resistant envelopes, or storage trust.
10
+
11
+ That plumbing leaked into the first version of #10628 while solving #10250. #10276 gave us the reusable low-level synth mechanism; this PR adds the missing storage-facing layer so the session fix can become the easy change.
12
+
13
+ ## What
14
+
15
+ Add a small `PersistedValueCodec` over `HandleSynths`:
16
+
17
+ ```php
18
+ $stored = $codec->encodeForStorage($value, $component, $path, $storageKey);
19
+ $value = $codec->decodeFromStorage($stored, $component, $path, $storageKey);
20
+ ```
21
+
22
+ The codec:
23
+
24
+ - leaves primitives and JSON-native arrays untouched;
25
+ - recursively dehydrates values that require a registered Livewire synth;
26
+ - owns a strict, versioned envelope so ordinary synth-shaped arrays are never interpreted as metadata;
27
+ - signs encoded envelopes with the application encryption key and binds the signature to the caller's resolved storage key;
28
+ - reconstructs `ComponentContext` internally;
29
+ - preserves nested values and registered custom synths;
30
+ - rejects unsigned, modified, wrong-version, or wrong-scope envelopes before `HandleSynths::hydrate()` is reachable.
31
+ - converts authentic values whose synthesizer is no longer available into recoverable corrupt state.
32
+
33
+ ## Trust boundary
34
+
35
+ This is intentionally not a general-purpose hydrator. Persisted values can originate from client-writable Livewire properties even when the eventual storage backend is trusted, so storage trust alone is insufficient. The codec authenticates its own output before hydration, using the same application-key security boundary as Livewire snapshots.
36
+
37
+ Browser snapshots retain their existing checksum, while URLs and request updates remain on the narrower type-directed `hydrateForUpdate()` path. No arbitrary request value can manufacture a decodable persisted synth envelope.
38
+
39
+ ## Progressive commits
40
+
41
+ 1. 🛹 — round-trip a Collection through an authenticated JSON envelope and prove unsigned envelopes never hydrate.
42
+ 2. 🚲 — define nested/custom synth behavior, strict envelope compatibility, storage-key sharing/scoping, tamper rejection, and outdated-synth recovery.
43
+
44
+ ## Verification
45
+
46
+ - Focused codec coverage: 12 tests, 19 assertions.
47
+ - Full stacked unit suite: 1,504 tests, 4,251 assertions; 13 existing skips and 3 existing incomplete tests.
48
+ - Independent review confirmed the original unsigned design was exploitable through a client-authored `ModelSynth` envelope; the signed design rejects that path before hydration under both JSON and PHP serializers.
49
+ - Built production assets before the complete unit run.
50
+
51
+ No user-facing behavior changes in this prerequisite PR. #10628 is the first consumer and retains the original implementation credit to @joshhanley.
52
+
53
+ ## Task
54
+
55
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `16c5b608ab42`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/livewire__livewire-10630/solution/patch.diff ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/src/Mechanisms/HandleSynths/CorruptPersistedValueException.php b/src/Mechanisms/HandleSynths/CorruptPersistedValueException.php
2
+ new file mode 100644
3
+ index 00000000..4562457f
4
+ --- /dev/null
5
+ +++ b/src/Mechanisms/HandleSynths/CorruptPersistedValueException.php
6
+ @@ -0,0 +1,11 @@
7
+ +<?php
8
+ +
9
+ +namespace Livewire\Mechanisms\HandleSynths;
10
+ +
11
+ +class CorruptPersistedValueException extends \Exception
12
+ +{
13
+ + public function __construct($previous = null)
14
+ + {
15
+ + parent::__construct('Livewire encountered corrupt persisted property data.', previous: $previous);
16
+ + }
17
+ +}
18
+ diff --git a/src/Mechanisms/HandleSynths/PersistedValueCodec.php b/src/Mechanisms/HandleSynths/PersistedValueCodec.php
19
+ new file mode 100644
20
+ index 00000000..21748a60
21
+ --- /dev/null
22
+ +++ b/src/Mechanisms/HandleSynths/PersistedValueCodec.php
23
+ @@ -0,0 +1,105 @@
24
+ +<?php
25
+ +
26
+ +namespace Livewire\Mechanisms\HandleSynths;
27
+ +
28
+ +use Livewire\Drawer\Utils;
29
+ +use Livewire\Mechanisms\HandleComponents\ComponentContext;
30
+ +
31
+ +class PersistedValueCodec
32
+ +{
33
+ + const KEY = '__livewire_persisted';
34
+ +
35
+ + const VERSION = 1;
36
+ +
37
+ + public function __construct(protected HandleSynths $synths) {}
38
+ +
39
+ + public function encodeForStorage($value, $component, $path, $key)
40
+ + {
41
+ + if (! $this->requiresSynthesis($value)) return $value;
42
+ +
43
+ + $encoded = $this->synths->dehydrate(
44
+ + $value,
45
+ + new ComponentContext($component),
46
+ + $path,
47
+ + );
48
+ +
49
+ + return [
50
+ + static::KEY => [
51
+ + 'version' => static::VERSION,
52
+ + 'value' => $encoded,
53
+ + 'signature' => $this->signatureFor($encoded, $key),
54
+ + ],
55
+ + ];
56
+ + }
57
+ +
58
+ + public function decodeFromStorage($value, $component, $path, $key)
59
+ + {
60
+ + if (! $this->isEnvelope($value)) return $value;
61
+ +
62
+ + $envelope = $value[static::KEY];
63
+ +
64
+ + if (! $this->isValidEnvelope($envelope, $key)) {
65
+ + throw new CorruptPersistedValueException;
66
+ + }
67
+ +
68
+ + try {
69
+ + return $this->synths->hydrate(
70
+ + $envelope['value'],
71
+ + new ComponentContext($component),
72
+ + $path,
73
+ + );
74
+ + } catch (\Throwable $e) {
75
+ + throw new CorruptPersistedValueException($e);
76
+ + }
77
+ + }
78
+ +
79
+ + protected function isEnvelope($value)
80
+ + {
81
+ + return is_array($value)
82
+ + && count($value) === 1
83
+ + && array_key_exists(static::KEY, $value);
84
+ + }
85
+ +
86
+ + protected function isValidEnvelope($envelope, $key)
87
+ + {
88
+ + if (! is_array($envelope) || count($envelope) !== 3) return false;
89
+ +
90
+ + if (($envelope['version'] ?? null) !== static::VERSION) return false;
91
+ +
92
+ + if (! array_key_exists('value', $envelope)) return false;
93
+ +
94
+ + if (! Utils::isSyntheticTuple($envelope['value'])) return false;
95
+ +
96
+ + if (! is_string($signature = $envelope['signature'] ?? null)) return false;
97
+ +
98
+ + return hash_equals(
99
+ + $this->signatureFor($envelope['value'], $key),
100
+ + $signature,
101
+ + );
102
+ + }
103
+ +
104
+ + protected function signatureFor($value, $key)
105
+ + {
106
+ + $payload = json_encode([
107
+ + 'type' => 'livewire-persisted-value',
108
+ + 'version' => static::VERSION,
109
+ + 'key' => $key,
110
+ + 'value' => $value,
111
+ + ], JSON_THROW_ON_ERROR);
112
+ +
113
+ + return hash_hmac('sha256', $payload, app('encrypter')->getKey());
114
+ + }
115
+ +
116
+ + protected function requiresSynthesis($value)
117
+ + {
118
+ + if (Utils::isAPrimitive($value)) return false;
119
+ +
120
+ + if (! is_array($value)) return true;
121
+ +
122
+ + foreach ($value as $child) {
123
+ + if ($this->requiresSynthesis($child)) return true;
124
+ + }
125
+ +
126
+ + return false;
127
+ + }
128
+ +}
129
+ diff --git a/src/Mechanisms/HandleSynths/PersistedValueCodecUnitTest.php b/src/Mechanisms/HandleSynths/PersistedValueCodecUnitTest.php
130
+ new file mode 100644
131
+ index 00000000..b43f43d1
132
+ --- /dev/null
133
+ +++ b/src/Mechanisms/HandleSynths/PersistedValueCodecUnitTest.php
134
+ @@ -0,0 +1,197 @@
135
+ +<?php
136
+ +
137
+ +namespace Livewire\Mechanisms\HandleSynths;
138
+ +
139
+ +use Illuminate\Support\Carbon;
140
+ +use Illuminate\Support\Collection;
141
+ +use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth;
142
+ +use Tests\TestComponent;
143
+ +
144
+ +class PersistedValueCodecUnitTest extends \Tests\TestCase
145
+ +{
146
+ + public function test_a_collection_round_trips_through_json_storage()
147
+ + {
148
+ + $codec = app(PersistedValueCodec::class);
149
+ + $component = new TestComponent;
150
+ +
151
+ + $encoded = $codec->encodeForStorage(collect([1, 2, 3]), $component, 'items', 'session.items');
152
+ + $stored = json_decode(json_encode($encoded), true);
153
+ + $decoded = $codec->decodeFromStorage($stored, $component, 'items', 'session.items');
154
+ +
155
+ + $this->assertInstanceOf(Collection::class, $decoded);
156
+ + $this->assertSame([1, 2, 3], $decoded->all());
157
+ + }
158
+ +
159
+ + public function test_json_safe_values_are_not_encoded()
160
+ + {
161
+ + $codec = app(PersistedValueCodec::class);
162
+ + $component = new TestComponent;
163
+ + $value = ['search' => '', 'tags' => [1, 2], 'enabled' => true];
164
+ +
165
+ + $this->assertSame($value, $codec->encodeForStorage($value, $component, 'filters', 'session.filters'));
166
+ + $this->assertSame($value, $codec->decodeFromStorage($value, $component, 'filters', 'session.filters'));
167
+ + }
168
+ +
169
+ + public function test_an_unsigned_envelope_is_never_hydrated()
170
+ + {
171
+ + $codec = app(PersistedValueCodec::class);
172
+ + $component = new TestComponent;
173
+ + $forged = [
174
+ + PersistedValueCodec::KEY => [
175
+ + 'version' => PersistedValueCodec::VERSION,
176
+ + 'value' => [['secret'], ['s' => 'clctn', 'class' => Collection::class]],
177
+ + ],
178
+ + ];
179
+ +
180
+ + $this->expectException(CorruptPersistedValueException::class);
181
+ +
182
+ + $codec->decodeFromStorage($forged, $component, 'items', 'session.items');
183
+ + }
184
+ +
185
+ + public function test_nested_synthesized_values_round_trip_through_json_storage()
186
+ + {
187
+ + $codec = app(PersistedValueCodec::class);
188
+ + $component = new TestComponent;
189
+ + $date = Carbon::parse('2026-01-15 10:00:00');
190
+ + $value = ['items' => collect([1, 2]), 'createdAt' => $date];
191
+ +
192
+ + $encoded = $codec->encodeForStorage($value, $component, 'state', 'session.state');
193
+ + $stored = json_decode(json_encode($encoded), true);
194
+ + $decoded = $codec->decodeFromStorage($stored, $component, 'state', 'session.state');
195
+ +
196
+ + $this->assertInstanceOf(Collection::class, $decoded['items']);
197
+ + $this->assertSame([1, 2], $decoded['items']->all());
198
+ + $this->assertInstanceOf(Carbon::class, $decoded['createdAt']);
199
+ + $this->assertTrue($decoded['createdAt']->equalTo($date));
200
+ + }
201
+ +
202
+ + public function test_registered_custom_synths_round_trip_through_json_storage()
203
+ + {
204
+ + app(HandleSynths::class)->registerSynth(PersistedValueSynth::class);
205
+ +
206
+ + $codec = app(PersistedValueCodec::class);
207
+ + $component = new TestComponent;
208
+ +
209
+ + $encoded = $codec->encodeForStorage(new PersistedValue('stored'), $component, 'value', 'session.value');
210
+ + $stored = json_decode(json_encode($encoded), true);
211
+ + $decoded = $codec->decodeFromStorage($stored, $component, 'value', 'session.value');
212
+ +
213
+ + $this->assertInstanceOf(PersistedValue::class, $decoded);
214
+ + $this->assertSame('stored', $decoded->value);
215
+ + }
216
+ +
217
+ + public function test_bare_synth_tuples_are_not_decoded()
218
+ + {
219
+ + $codec = app(PersistedValueCodec::class);
220
+ + $component = new TestComponent;
221
+ + $tuple = [['one', 'two'], ['s' => 'clctn', 'class' => Collection::class]];
222
+ +
223
+ + $this->assertSame($tuple, $codec->decodeFromStorage($tuple, $component, 'items', 'session.items'));
224
+ + }
225
+ +
226
+ + public function test_envelopes_with_sibling_application_data_are_not_decoded()
227
+ + {
228
+ + $codec = app(PersistedValueCodec::class);
229
+ + $component = new TestComponent;
230
+ + $encoded = $codec->encodeForStorage(collect([1, 2]), $component, 'items', 'session.items');
231
+ + $withSiblingData = [...$encoded, 'application' => 'value'];
232
+ +
233
+ + $this->assertSame($withSiblingData, $codec->decodeFromStorage($withSiblingData, $component, 'items', 'session.items'));
234
+ + }
235
+ +
236
+ + public function test_unsupported_envelope_versions_are_rejected()
237
+ + {
238
+ + $codec = app(PersistedValueCodec::class);
239
+ + $component = new TestComponent;
240
+ + $encoded = $codec->encodeForStorage(collect([1, 2]), $component, 'items', 'session.items');
241
+ + $encoded[PersistedValueCodec::KEY]['version']++;
242
+ +
243
+ + $this->expectException(CorruptPersistedValueException::class);
244
+ +
245
+ + $codec->decodeFromStorage($encoded, $component, 'items', 'session.items');
246
+ + }
247
+ +
248
+ + public function test_tampered_envelopes_are_rejected_before_hydration()
249
+ + {
250
+ + $codec = app(PersistedValueCodec::class);
251
+ + $component = new TestComponent;
252
+ + $encoded = $codec->encodeForStorage(collect([1, 2]), $component, 'items', 'session.items');
253
+ + $encoded[PersistedValueCodec::KEY]['value'][0][] = 3;
254
+ +
255
+ + $this->expectException(CorruptPersistedValueException::class);
256
+ +
257
+ + $codec->decodeFromStorage($encoded, $component, 'items', 'session.items');
258
+ + }
259
+ +
260
+ + public function test_signatures_are_bound_to_the_storage_key()
261
+ + {
262
+ + $codec = app(PersistedValueCodec::class);
263
+ + $component = new TestComponent;
264
+ + $encoded = $codec->encodeForStorage(collect([1, 2]), $component, 'items', 'session.items');
265
+ +
266
+ + $this->expectException(CorruptPersistedValueException::class);
267
+ +
268
+ + $codec->decodeFromStorage($encoded, $component, 'items', 'session.other');
269
+ + }
270
+ +
271
+ + public function test_a_shared_storage_key_can_be_decoded_by_another_component_property()
272
+ + {
273
+ + $codec = app(PersistedValueCodec::class);
274
+ + $encoded = $codec->encodeForStorage(collect([1, 2]), new TestComponent, 'items', 'shared');
275
+ +
276
+ + $decoded = $codec->decodeFromStorage($encoded, new OtherTestComponent, 'renamed', 'shared');
277
+ +
278
+ + $this->assertInstanceOf(Collection::class, $decoded);
279
+ + $this->assertSame([1, 2], $decoded->all());
280
+ + }
281
+ +
282
+ + public function test_hydration_failures_are_reported_as_corrupt_persisted_values()
283
+ + {
284
+ + app(HandleSynths::class)->registerSynth(PersistedValueSynth::class);
285
+ +
286
+ + $component = new TestComponent;
287
+ + $encoded = app(PersistedValueCodec::class)
288
+ + ->encodeForStorage(new PersistedValue('stored'), $component, 'value', 'session.value');
289
+ + $codecWithoutCustomSynth = new PersistedValueCodec(new HandleSynths);
290
+ +
291
+ + try {
292
+ + $codecWithoutCustomSynth->decodeFromStorage($encoded, $component, 'value', 'session.value');
293
+ + } catch (CorruptPersistedValueException $e) {
294
+ + $this->assertStringContainsString('No synthesizer found', $e->getPrevious()->getMessage());
295
+ +
296
+ + return;
297
+ + }
298
+ +
299
+ + $this->fail('The outdated persisted value was hydrated.');
300
+ + }
301
+ +}
302
+ +
303
+ +class OtherTestComponent extends TestComponent
304
+ +{
305
+ + //
306
+ +}
307
+ +
308
+ +class PersistedValue
309
+ +{
310
+ + public function __construct(public string $value) {}
311
+ +}
312
+ +
313
+ +class PersistedValueSynth extends Synth
314
+ +{
315
+ + public static $key = 'persisted-value';
316
+ +
317
+ + public static function match($target)
318
+ + {
319
+ + return $target instanceof PersistedValue;
320
+ + }
321
+ +
322
+ + public function dehydrate($target)
323
+ + {
324
+ + return [$target->value, []];
325
+ + }
326
+ +
327
+ + public function hydrate($value)
328
+ + {
329
+ + return new PersistedValue($value);
330
+ + }
331
+ +}
tasks/livewire__livewire-10630/solution/solve.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euxo pipefail
3
+ cd /workspace
4
+ git config --global --add safe.directory /workspace
5
+ PATCH="$(dirname "$0")/patch.diff"
6
+ git apply --verbose --reject "$PATCH"
tasks/livewire__livewire-10630/task.toml ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/livewire__livewire-10630"
5
+ description = "[4.x] Add a trusted-storage codec for synthesized values"
6
+
7
+ [metadata]
8
+ difficulty = "large"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "livewire",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "livewire/livewire"
19
+ ref = "16c5b608ab422f8135e16e5cc1e0af3c72d3d1cc"
20
+ reference = "https://github.com/livewire/livewire/pull/10630"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:51.550784+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:10f5f2637187f7ff1d430f06eb11abdee271358d3e4f76ca3014802b093ff0b2"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-08-29T16:07:47Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "src/Mechanisms/HandleSynths/CorruptPersistedValueException.php",
34
+ "src/Mechanisms/HandleSynths/PersistedValueCodec.php",
35
+ "src/Mechanisms/HandleSynths/PersistedValueCodecUnitTest.php",
36
+ ]
37
+ bootstrap_image = "python:3.12-slim"
38
+
39
+ [metadata.repo2env.reward_calibration]
40
+ baseline_reward = 0.0
41
+ loc_changed = 313
42
+ difficulty = "large"
43
+
44
+ [metadata.repo2env.evaluation]
45
+ schema_version = "1"
46
+ status = "unverified"
47
+ stage = "generation"
48
+ reason_codes = [
49
+ "validation_not_run",
50
+ ]
51
+ detail = "Generated task; validation has not been established."
52
+ provenance = "unknown"
53
+ evidence = []
54
+
55
+ [metadata.repo2env.reproducibility]
56
+ mode = "inline_dockerfile"
57
+ image_ref = "python:3.12-slim"
58
+ image_tag = "python:3.12-slim"
59
+ image_visibility = "public"
60
+ pushed_at = "2026-11-16T16:20:01.367919+00:00"
61
+ pushed_by = "scalingX"
62
+ inline_recipe_sha256 = "sha256:9af8b1153630dccc748aa45dfeca24396f4fb64150581449f871d7996207c013"
63
+ inline_recipe_lines = 37
64
+ inline_recipe_source = "user_dockerfile"
65
+
66
+ [agent]
67
+ timeout_sec = 1800.0
68
+
69
+ [verifier]
70
+ timeout_sec = 300.0
tasks/livewire__livewire-10630/tests/capture.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone PR-diff capture without executing workspace Git configuration.
2
+
3
+ The emitted task uses a regular clone with a pinned base commit. Only its
4
+ object store is read: refs, index, config, hooks and replacement refs are not
5
+ used. This is a configuration boundary, not a sandbox for a malicious process
6
+ that can modify the verifier, binaries or object store while capture runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+
22
+ def capture(workspace: Path, base_commit: str) -> bytes:
23
+ """Capture tracked and new files through a fresh private Git index."""
24
+ if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit):
25
+ raise ValueError("Expected the task's pinned SHA-1 base commit")
26
+ objects = workspace.resolve() / ".git" / "objects"
27
+ if not objects.is_dir():
28
+ raise ValueError("The task's cloned Git object store is missing")
29
+ git = shutil.which("git", path=os.defpath)
30
+ if git is None:
31
+ raise FileNotFoundError("System git is unavailable")
32
+ with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary:
33
+ private = Path(temporary)
34
+ # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs,
35
+ # system/global includes, user attributes, templates or credential env.
36
+ env = {
37
+ "PATH": os.defpath,
38
+ "HOME": temporary,
39
+ "XDG_CONFIG_HOME": temporary,
40
+ "GIT_CONFIG_NOSYSTEM": "1",
41
+ "GIT_CONFIG_GLOBAL": os.devnull,
42
+ "GIT_ATTR_NOSYSTEM": "1",
43
+ "GIT_NO_REPLACE_OBJECTS": "1",
44
+ "GIT_NO_LAZY_FETCH": "1",
45
+ "GIT_TERMINAL_PROMPT": "0",
46
+ "LC_ALL": "C",
47
+ }
48
+ subprocess.run(
49
+ [git, "init", "--quiet", "--template=", str(private / "repository")],
50
+ env=env,
51
+ cwd=private,
52
+ check=True,
53
+ capture_output=True,
54
+ timeout=60,
55
+ )
56
+ env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False)
57
+ command = [
58
+ git,
59
+ f"--git-dir={private / 'repository/.git'}",
60
+ f"--work-tree={workspace.resolve()}",
61
+ ]
62
+
63
+ def run(*args: str) -> bytes:
64
+ return subprocess.run(
65
+ [*command, *args],
66
+ env=env,
67
+ cwd=workspace,
68
+ check=True,
69
+ capture_output=True,
70
+ timeout=60,
71
+ ).stdout
72
+
73
+ run("read-tree", f"{base_commit}^{{tree}}")
74
+ # All filter drivers are undefined in the private configuration. The
75
+ # workspace's clean filters, fsmonitor and hooks cannot be invoked.
76
+ run("add", "--all", "--", ".")
77
+ return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
78
+
79
+
80
+ def main(argv: list[str] | None = None) -> int:
81
+ parser = argparse.ArgumentParser(description=__doc__)
82
+ parser.add_argument("workspace", type=Path)
83
+ parser.add_argument("base_commit")
84
+ args = parser.parse_args(argv)
85
+ try:
86
+ patch = capture(args.workspace, args.base_commit)
87
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
88
+ # Do not echo child stderr: it may contain workspace-controlled data.
89
+ sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n")
90
+ return 1
91
+ sys.stdout.buffer.write(patch)
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
tasks/livewire__livewire-10630/tests/instruction.md ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** [4.x] Add a trusted-storage codec for synthesized values
4
+
5
+ ## Description
6
+
7
+ ## Why
8
+
9
+ Features that persist Livewire property values outside the normal browser snapshot need the synth system, but should not each learn about `ComponentContext`, recursive synth tuples, collision-resistant envelopes, or storage trust.
10
+
11
+ That plumbing leaked into the first version of #10628 while solving #10250. #10276 gave us the reusable low-level synth mechanism; this PR adds the missing storage-facing layer so the session fix can become the easy change.
12
+
13
+ ## What
14
+
15
+ Add a small `PersistedValueCodec` over `HandleSynths`:
16
+
17
+ ```php
18
+ $stored = $codec->encodeForStorage($value, $component, $path, $storageKey);
19
+ $value = $codec->decodeFromStorage($stored, $component, $path, $storageKey);
20
+ ```
21
+
22
+ The codec:
23
+
24
+ - leaves primitives and JSON-native arrays untouched;
25
+ - recursively dehydrates values that require a registered Livewire synth;
26
+ - owns a strict, versioned envelope so ordinary synth-shaped arrays are never interpreted as metadata;
27
+ - signs encoded envelopes with the application encryption key and binds the signature to the caller's resolved storage key;
28
+ - reconstructs `ComponentContext` internally;
29
+ - preserves nested values and registered custom synths;
30
+ - rejects unsigned, modified, wrong-version, or wrong-scope envelopes before `HandleSynths::hydrate()` is reachable.
31
+ - converts authentic values whose synthesizer is no longer available into recoverable corrupt state.
32
+
33
+ ## Trust boundary
34
+
35
+ This is intentionally not a general-purpose hydrator. Persisted values can originate from client-writable Livewire properties even when the eventual storage backend is trusted, so storage trust alone is insufficient. The codec authenticates its own output before hydration, using the same application-key security boundary as Livewire snapshots.
36
+
37
+ Browser snapshots retain their existing checksum, while URLs and request updates remain on the narrower type-directed `hydrateForUpdate()` path. No arbitrary request value can manufacture a decodable persisted synth envelope.
38
+
39
+ ## Progressive commits
40
+
41
+ 1. 🛹 — round-trip a Collection through an authenticated JSON envelope and prove unsigned envelopes never hydrate.
42
+ 2. 🚲 — define nested/custom synth behavior, strict envelope compatibility, storage-key sharing/scoping, tamper rejection, and outdated-synth recovery.
43
+
44
+ ## Verification
45
+
46
+ - Focused codec coverage: 12 tests, 19 assertions.
47
+ - Full stacked unit suite: 1,504 tests, 4,251 assertions; 13 existing skips and 3 existing incomplete tests.
48
+ - Independent review confirmed the original unsigned design was exploitable through a client-authored `ModelSynth` envelope; the signed design rejects that path before hydration under both JSON and PHP serializers.
49
+ - Built production assets before the complete unit run.
50
+
51
+ No user-facing behavior changes in this prerequisite PR. #10628 is the first consumer and retains the original implementation credit to @joshhanley.
52
+
53
+ ## Task
54
+
55
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `16c5b608ab42`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/livewire__livewire-10630/tests/oracle.patch ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/src/Mechanisms/HandleSynths/CorruptPersistedValueException.php b/src/Mechanisms/HandleSynths/CorruptPersistedValueException.php
2
+ new file mode 100644
3
+ index 00000000..4562457f
4
+ --- /dev/null
5
+ +++ b/src/Mechanisms/HandleSynths/CorruptPersistedValueException.php
6
+ @@ -0,0 +1,11 @@
7
+ +<?php
8
+ +
9
+ +namespace Livewire\Mechanisms\HandleSynths;
10
+ +
11
+ +class CorruptPersistedValueException extends \Exception
12
+ +{
13
+ + public function __construct($previous = null)
14
+ + {
15
+ + parent::__construct('Livewire encountered corrupt persisted property data.', previous: $previous);
16
+ + }
17
+ +}
18
+ diff --git a/src/Mechanisms/HandleSynths/PersistedValueCodec.php b/src/Mechanisms/HandleSynths/PersistedValueCodec.php
19
+ new file mode 100644
20
+ index 00000000..21748a60
21
+ --- /dev/null
22
+ +++ b/src/Mechanisms/HandleSynths/PersistedValueCodec.php
23
+ @@ -0,0 +1,105 @@
24
+ +<?php
25
+ +
26
+ +namespace Livewire\Mechanisms\HandleSynths;
27
+ +
28
+ +use Livewire\Drawer\Utils;
29
+ +use Livewire\Mechanisms\HandleComponents\ComponentContext;
30
+ +
31
+ +class PersistedValueCodec
32
+ +{
33
+ + const KEY = '__livewire_persisted';
34
+ +
35
+ + const VERSION = 1;
36
+ +
37
+ + public function __construct(protected HandleSynths $synths) {}
38
+ +
39
+ + public function encodeForStorage($value, $component, $path, $key)
40
+ + {
41
+ + if (! $this->requiresSynthesis($value)) return $value;
42
+ +
43
+ + $encoded = $this->synths->dehydrate(
44
+ + $value,
45
+ + new ComponentContext($component),
46
+ + $path,
47
+ + );
48
+ +
49
+ + return [
50
+ + static::KEY => [
51
+ + 'version' => static::VERSION,
52
+ + 'value' => $encoded,
53
+ + 'signature' => $this->signatureFor($encoded, $key),
54
+ + ],
55
+ + ];
56
+ + }
57
+ +
58
+ + public function decodeFromStorage($value, $component, $path, $key)
59
+ + {
60
+ + if (! $this->isEnvelope($value)) return $value;
61
+ +
62
+ + $envelope = $value[static::KEY];
63
+ +
64
+ + if (! $this->isValidEnvelope($envelope, $key)) {
65
+ + throw new CorruptPersistedValueException;
66
+ + }
67
+ +
68
+ + try {
69
+ + return $this->synths->hydrate(
70
+ + $envelope['value'],
71
+ + new ComponentContext($component),
72
+ + $path,
73
+ + );
74
+ + } catch (\Throwable $e) {
75
+ + throw new CorruptPersistedValueException($e);
76
+ + }
77
+ + }
78
+ +
79
+ + protected function isEnvelope($value)
80
+ + {
81
+ + return is_array($value)
82
+ + && count($value) === 1
83
+ + && array_key_exists(static::KEY, $value);
84
+ + }
85
+ +
86
+ + protected function isValidEnvelope($envelope, $key)
87
+ + {
88
+ + if (! is_array($envelope) || count($envelope) !== 3) return false;
89
+ +
90
+ + if (($envelope['version'] ?? null) !== static::VERSION) return false;
91
+ +
92
+ + if (! array_key_exists('value', $envelope)) return false;
93
+ +
94
+ + if (! Utils::isSyntheticTuple($envelope['value'])) return false;
95
+ +
96
+ + if (! is_string($signature = $envelope['signature'] ?? null)) return false;
97
+ +
98
+ + return hash_equals(
99
+ + $this->signatureFor($envelope['value'], $key),
100
+ + $signature,
101
+ + );
102
+ + }
103
+ +
104
+ + protected function signatureFor($value, $key)
105
+ + {
106
+ + $payload = json_encode([
107
+ + 'type' => 'livewire-persisted-value',
108
+ + 'version' => static::VERSION,
109
+ + 'key' => $key,
110
+ + 'value' => $value,
111
+ + ], JSON_THROW_ON_ERROR);
112
+ +
113
+ + return hash_hmac('sha256', $payload, app('encrypter')->getKey());
114
+ + }
115
+ +
116
+ + protected function requiresSynthesis($value)
117
+ + {
118
+ + if (Utils::isAPrimitive($value)) return false;
119
+ +
120
+ + if (! is_array($value)) return true;
121
+ +
122
+ + foreach ($value as $child) {
123
+ + if ($this->requiresSynthesis($child)) return true;
124
+ + }
125
+ +
126
+ + return false;
127
+ + }
128
+ +}
129
+ diff --git a/src/Mechanisms/HandleSynths/PersistedValueCodecUnitTest.php b/src/Mechanisms/HandleSynths/PersistedValueCodecUnitTest.php
130
+ new file mode 100644
131
+ index 00000000..b43f43d1
132
+ --- /dev/null
133
+ +++ b/src/Mechanisms/HandleSynths/PersistedValueCodecUnitTest.php
134
+ @@ -0,0 +1,197 @@
135
+ +<?php
136
+ +
137
+ +namespace Livewire\Mechanisms\HandleSynths;
138
+ +
139
+ +use Illuminate\Support\Carbon;
140
+ +use Illuminate\Support\Collection;
141
+ +use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth;
142
+ +use Tests\TestComponent;
143
+ +
144
+ +class PersistedValueCodecUnitTest extends \Tests\TestCase
145
+ +{
146
+ + public function test_a_collection_round_trips_through_json_storage()
147
+ + {
148
+ + $codec = app(PersistedValueCodec::class);
149
+ + $component = new TestComponent;
150
+ +
151
+ + $encoded = $codec->encodeForStorage(collect([1, 2, 3]), $component, 'items', 'session.items');
152
+ + $stored = json_decode(json_encode($encoded), true);
153
+ + $decoded = $codec->decodeFromStorage($stored, $component, 'items', 'session.items');
154
+ +
155
+ + $this->assertInstanceOf(Collection::class, $decoded);
156
+ + $this->assertSame([1, 2, 3], $decoded->all());
157
+ + }
158
+ +
159
+ + public function test_json_safe_values_are_not_encoded()
160
+ + {
161
+ + $codec = app(PersistedValueCodec::class);
162
+ + $component = new TestComponent;
163
+ + $value = ['search' => '', 'tags' => [1, 2], 'enabled' => true];
164
+ +
165
+ + $this->assertSame($value, $codec->encodeForStorage($value, $component, 'filters', 'session.filters'));
166
+ + $this->assertSame($value, $codec->decodeFromStorage($value, $component, 'filters', 'session.filters'));
167
+ + }
168
+ +
169
+ + public function test_an_unsigned_envelope_is_never_hydrated()
170
+ + {
171
+ + $codec = app(PersistedValueCodec::class);
172
+ + $component = new TestComponent;
173
+ + $forged = [
174
+ + PersistedValueCodec::KEY => [
175
+ + 'version' => PersistedValueCodec::VERSION,
176
+ + 'value' => [['secret'], ['s' => 'clctn', 'class' => Collection::class]],
177
+ + ],
178
+ + ];
179
+ +
180
+ + $this->expectException(CorruptPersistedValueException::class);
181
+ +
182
+ + $codec->decodeFromStorage($forged, $component, 'items', 'session.items');
183
+ + }
184
+ +
185
+ + public function test_nested_synthesized_values_round_trip_through_json_storage()
186
+ + {
187
+ + $codec = app(PersistedValueCodec::class);
188
+ + $component = new TestComponent;
189
+ + $date = Carbon::parse('2026-01-15 10:00:00');
190
+ + $value = ['items' => collect([1, 2]), 'createdAt' => $date];
191
+ +
192
+ + $encoded = $codec->encodeForStorage($value, $component, 'state', 'session.state');
193
+ + $stored = json_decode(json_encode($encoded), true);
194
+ + $decoded = $codec->decodeFromStorage($stored, $component, 'state', 'session.state');
195
+ +
196
+ + $this->assertInstanceOf(Collection::class, $decoded['items']);
197
+ + $this->assertSame([1, 2], $decoded['items']->all());
198
+ + $this->assertInstanceOf(Carbon::class, $decoded['createdAt']);
199
+ + $this->assertTrue($decoded['createdAt']->equalTo($date));
200
+ + }
201
+ +
202
+ + public function test_registered_custom_synths_round_trip_through_json_storage()
203
+ + {
204
+ + app(HandleSynths::class)->registerSynth(PersistedValueSynth::class);
205
+ +
206
+ + $codec = app(PersistedValueCodec::class);
207
+ + $component = new TestComponent;
208
+ +
209
+ + $encoded = $codec->encodeForStorage(new PersistedValue('stored'), $component, 'value', 'session.value');
210
+ + $stored = json_decode(json_encode($encoded), true);
211
+ + $decoded = $codec->decodeFromStorage($stored, $component, 'value', 'session.value');
212
+ +
213
+ + $this->assertInstanceOf(PersistedValue::class, $decoded);
214
+ + $this->assertSame('stored', $decoded->value);
215
+ + }
216
+ +
217
+ + public function test_bare_synth_tuples_are_not_decoded()
218
+ + {
219
+ + $codec = app(PersistedValueCodec::class);
220
+ + $component = new TestComponent;
221
+ + $tuple = [['one', 'two'], ['s' => 'clctn', 'class' => Collection::class]];
222
+ +
223
+ + $this->assertSame($tuple, $codec->decodeFromStorage($tuple, $component, 'items', 'session.items'));
224
+ + }
225
+ +
226
+ + public function test_envelopes_with_sibling_application_data_are_not_decoded()
227
+ + {
228
+ + $codec = app(PersistedValueCodec::class);
229
+ + $component = new TestComponent;
230
+ + $encoded = $codec->encodeForStorage(collect([1, 2]), $component, 'items', 'session.items');
231
+ + $withSiblingData = [...$encoded, 'application' => 'value'];
232
+ +
233
+ + $this->assertSame($withSiblingData, $codec->decodeFromStorage($withSiblingData, $component, 'items', 'session.items'));
234
+ + }
235
+ +
236
+ + public function test_unsupported_envelope_versions_are_rejected()
237
+ + {
238
+ + $codec = app(PersistedValueCodec::class);
239
+ + $component = new TestComponent;
240
+ + $encoded = $codec->encodeForStorage(collect([1, 2]), $component, 'items', 'session.items');
241
+ + $encoded[PersistedValueCodec::KEY]['version']++;
242
+ +
243
+ + $this->expectException(CorruptPersistedValueException::class);
244
+ +
245
+ + $codec->decodeFromStorage($encoded, $component, 'items', 'session.items');
246
+ + }
247
+ +
248
+ + public function test_tampered_envelopes_are_rejected_before_hydration()
249
+ + {
250
+ + $codec = app(PersistedValueCodec::class);
251
+ + $component = new TestComponent;
252
+ + $encoded = $codec->encodeForStorage(collect([1, 2]), $component, 'items', 'session.items');
253
+ + $encoded[PersistedValueCodec::KEY]['value'][0][] = 3;
254
+ +
255
+ + $this->expectException(CorruptPersistedValueException::class);
256
+ +
257
+ + $codec->decodeFromStorage($encoded, $component, 'items', 'session.items');
258
+ + }
259
+ +
260
+ + public function test_signatures_are_bound_to_the_storage_key()
261
+ + {
262
+ + $codec = app(PersistedValueCodec::class);
263
+ + $component = new TestComponent;
264
+ + $encoded = $codec->encodeForStorage(collect([1, 2]), $component, 'items', 'session.items');
265
+ +
266
+ + $this->expectException(CorruptPersistedValueException::class);
267
+ +
268
+ + $codec->decodeFromStorage($encoded, $component, 'items', 'session.other');
269
+ + }
270
+ +
271
+ + public function test_a_shared_storage_key_can_be_decoded_by_another_component_property()
272
+ + {
273
+ + $codec = app(PersistedValueCodec::class);
274
+ + $encoded = $codec->encodeForStorage(collect([1, 2]), new TestComponent, 'items', 'shared');
275
+ +
276
+ + $decoded = $codec->decodeFromStorage($encoded, new OtherTestComponent, 'renamed', 'shared');
277
+ +
278
+ + $this->assertInstanceOf(Collection::class, $decoded);
279
+ + $this->assertSame([1, 2], $decoded->all());
280
+ + }
281
+ +
282
+ + public function test_hydration_failures_are_reported_as_corrupt_persisted_values()
283
+ + {
284
+ + app(HandleSynths::class)->registerSynth(PersistedValueSynth::class);
285
+ +
286
+ + $component = new TestComponent;
287
+ + $encoded = app(PersistedValueCodec::class)
288
+ + ->encodeForStorage(new PersistedValue('stored'), $component, 'value', 'session.value');
289
+ + $codecWithoutCustomSynth = new PersistedValueCodec(new HandleSynths);
290
+ +
291
+ + try {
292
+ + $codecWithoutCustomSynth->decodeFromStorage($encoded, $component, 'value', 'session.value');
293
+ + } catch (CorruptPersistedValueException $e) {
294
+ + $this->assertStringContainsString('No synthesizer found', $e->getPrevious()->getMessage());
295
+ +
296
+ + return;
297
+ + }
298
+ +
299
+ + $this->fail('The outdated persisted value was hydrated.');
300
+ + }
301
+ +}
302
+ +
303
+ +class OtherTestComponent extends TestComponent
304
+ +{
305
+ + //
306
+ +}
307
+ +
308
+ +class PersistedValue
309
+ +{
310
+ + public function __construct(public string $value) {}
311
+ +}
312
+ +
313
+ +class PersistedValueSynth extends Synth
314
+ +{
315
+ + public static $key = 'persisted-value';
316
+ +
317
+ + public static function match($target)
318
+ + {
319
+ + return $target instanceof PersistedValue;
320
+ + }
321
+ +
322
+ + public function dehydrate($target)
323
+ + {
324
+ + return [$target->value, []];
325
+ + }
326
+ +
327
+ + public function hydrate($value)
328
+ + {
329
+ + return new PersistedValue($value);
330
+ + }
331
+ +}
tasks/livewire__livewire-10630/tests/test.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -uxo pipefail
3
+ SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
4
+ cd /workspace
5
+ mkdir -p /logs/verifier
6
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json /logs/verifier/reward-details.json
7
+ CAPTURE_DIR="$(mktemp -d)" || exit 1
8
+ trap 'rm -rf -- "$CAPTURE_DIR"' EXIT
9
+ if ! python3 -I "$SCRIPT_DIR/capture.py" /workspace 16c5b608ab422f8135e16e5cc1e0af3c72d3d1cc > "$CAPTURE_DIR/predicted.patch"; then
10
+ echo "0.0" > /logs/verifier/reward.txt
11
+ printf '%s' '{"final_reward": 0.0, "evaluation_status": "graded", "eval_trustworthy": false, "capture_status": "error"}' > /logs/verifier/reward-details.json
12
+ exit 0
13
+ fi
14
+ rm -f /logs/verifier/predicted.patch
15
+ cp -- "$CAPTURE_DIR/predicted.patch" /logs/verifier/predicted.patch
16
+ : 'START_VERIFY_OUTPUT'
17
+ if ! python3 -I "$SCRIPT_DIR/verifier.py" \
18
+ "$SCRIPT_DIR/oracle.patch" \
19
+ "$CAPTURE_DIR/predicted.patch" \
20
+ "$SCRIPT_DIR/instruction.md"; then
21
+ rm -f /logs/verifier/reward.txt /logs/verifier/reward.json
22
+ printf '%s' '{"final_reward": null, "reward": null, "evaluation_status": "ungraded", "eval_trustworthy": false, "verifier_status": "error"}' > /logs/verifier/reward-details.json
23
+ fi
24
+ : 'END_VERIFY_OUTPUT'
25
+ exit 0
tasks/livewire__livewire-10630/tests/verifier.py ADDED
@@ -0,0 +1,737 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """In-container verifier for pr_diff tasks (6-component reward).
2
+
3
+ This module is the **standalone verifier** that runs inside the task's
4
+ Docker container, NOT a helper used at generation time. Generation emits
5
+ its source as ``tests/verifier.py``. Harbor delivers it at verify time,
6
+ and ``tests/test.sh`` invokes it with the oracle, predicted patch and instruction.
7
+
8
+ Reward = weighted sum of 6 components (5 deterministic + 1 required LLM):
9
+
10
+ format_valid (0 or 1) — predicted parses as a unified diff (guard)
11
+ size_sanity ([0, 1]) — min(oracle_loc, pred_loc) / max(...)
12
+ catches "rampage through the codebase"
13
+ file_targeting ([0, 1]) — F1 over changed-file sets (NOT Jaccard —
14
+ symmetric penalty over-punishes extras)
15
+ region_overlap ([0, 1]) — predicted hunks overlap oracle hunks
16
+ (strongest spatial-localization signal)
17
+ similarity ([0, 1]) — SequenceMatcher ratio over +/- lines only
18
+ (no free credit for context lines)
19
+ llm_judge ([0, 1] or null) — an LLM rates "does this address the issue?"
20
+ Anthropic Haiku by default; any OpenAI-
21
+ compatible server via ``R2E_JUDGE_ENDPOINT``.
22
+ null when the judge is unavailable
23
+ (no key or model, network, unreadable
24
+ reply) → ungraded, no reward file; a
25
+ reply without a valid score (refusal,
26
+ content filter, empty, no "score") → a
27
+ graded 0
28
+
29
+ Default weights: 0.00 / 0.08 / 0.12 / 0.20 / 0.10 / 0.50 (retuned from
30
+ the original 0.05 / 0.05 / 0.10 / 0.20 / 0.20 / 0.40 after a 23-task
31
+ pilot — see the comment block above ``_DEFAULT_WEIGHTS`` below).
32
+ Override per-task via ``task.toml.metadata`` or per-run via env vars
33
+ ``R2E_W_FORMAT`` / ``R2E_W_SIZE`` / ``R2E_W_FILE`` / ``R2E_W_REGION`` /
34
+ ``R2E_W_SIM`` / ``R2E_W_JUDGE`` (pass via harbor ``--ve`` so they
35
+ reach the verifier container).
36
+
37
+ Judge routing, also via ``--ve``: ``R2E_JUDGE_MODEL`` picks the model
38
+ (default Haiku); ``R2E_JUDGE_ENDPOINT`` points at an OpenAI-compatible
39
+ server (vLLM, Ollama, a gateway) and switches the request to
40
+ ``<endpoint>/chat/completions`` with a bearer token from
41
+ ``R2E_JUDGE_API_KEY`` — or a placeholder when unset, since self-hosted
42
+ servers ignore it. ``ANTHROPIC_API_KEY`` is only read on the default
43
+ route and is never sent to a custom endpoint.
44
+
45
+ Final reward is clipped to [0, 1] and additionally clamped to ≤ 0.40
46
+ when ``size_sanity < 0.10`` (catastrophic-size hard cap — stops a
47
+ charitable judge from inflating scores on wildly wrong-sized patches).
48
+
49
+ Outputs (mirrors `_pr_runtime_verifier.py` after #75):
50
+ /logs/verifier/reward.txt — single float (Harbor reads this);
51
+ graded runs only
52
+ /logs/verifier/reward-details.json — full component breakdown + status
53
+ (structured diagnostics; Harbor's `reward.json` schema is flat-numeric-
54
+ only, so the breakdown goes to the `reward-details.json` sidecar which
55
+ Harbor renders under Verifier Logs → Rewards)
56
+
57
+ Pure stdlib — uses only ``difflib``, ``json``, ``os``, ``re``,
58
+ ``urllib``, ``sys``. The same module is imported by the unit tests
59
+ under ``tests/test_pr_diff_verifier.py`` so the in-container behavior
60
+ stays in lockstep with what we test.
61
+ """
62
+
63
+ from __future__ import annotations
64
+
65
+ import argparse
66
+ import difflib
67
+ import json
68
+ import math
69
+ import os
70
+ import re
71
+ import sys
72
+ import urllib.error
73
+ import urllib.request
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Parsing helpers (shared by multiple components)
77
+ # ---------------------------------------------------------------------------
78
+
79
+ _DIFF_HEADER_RE = re.compile(r"^diff --git a/(\S+) b/(\S+)$")
80
+ _HUNK_HEADER_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
81
+ _FILE_MARKER_RE = re.compile(r"^(?:---|\+\+\+) ")
82
+ _INDEX_RE = re.compile(r"^index ")
83
+
84
+
85
+ def file_paths(diff: str) -> set[str]:
86
+ """Return the set of ``b/<path>`` paths touched by a unified diff."""
87
+ paths: set[str] = set()
88
+ for line in diff.splitlines():
89
+ m = _DIFF_HEADER_RE.match(line)
90
+ if m:
91
+ paths.add(m.group(2))
92
+ return paths
93
+
94
+
95
+ def hunk_ranges(diff: str) -> dict[str, list[tuple[int, int]]]:
96
+ """For each touched file, return list of (start_line, end_line) ranges
97
+ on the **post-change** side (the ``+`` numbers in ``@@ -X +Y @@``).
98
+ """
99
+ out: dict[str, list[tuple[int, int]]] = {}
100
+ current_file: str | None = None
101
+ for line in diff.splitlines():
102
+ m = _DIFF_HEADER_RE.match(line)
103
+ if m:
104
+ current_file = m.group(2)
105
+ out.setdefault(current_file, [])
106
+ continue
107
+ m = _HUNK_HEADER_RE.match(line)
108
+ if m and current_file is not None:
109
+ new_start = int(m.group(3))
110
+ new_count = int(m.group(4) or "1")
111
+ end = new_start + max(new_count - 1, 0)
112
+ out[current_file].append((new_start, end))
113
+ return out
114
+
115
+
116
+ def _normalize_changes_only(diff: str) -> list[str]:
117
+ """Return the +/- lines (the actual changes) for similarity scoring.
118
+
119
+ Drops:
120
+ - ``diff --git`` / ``index abc..def`` metadata
121
+ - ``@@ ... @@`` hunk markers (volatile line numbers)
122
+ - context lines (no +/- prefix) — these are unchanged code, scoring
123
+ them inflates similarity for trivial patches
124
+ Keeps file-marker lines (``--- a/foo`` / ``+++ b/foo``) so file identity
125
+ stays in the comparison; normalizes off the tab+timestamp suffix git
126
+ sometimes appends.
127
+ """
128
+ out: list[str] = []
129
+ for line in diff.splitlines():
130
+ if _DIFF_HEADER_RE.match(line) or _INDEX_RE.match(line):
131
+ continue
132
+ if _HUNK_HEADER_RE.match(line):
133
+ continue
134
+ if _FILE_MARKER_RE.match(line):
135
+ out.append(line.split("\t")[0].strip())
136
+ continue
137
+ # +/- lines (actual changes)
138
+ if line.startswith("+") or line.startswith("-"):
139
+ out.append(line)
140
+ return out
141
+
142
+
143
+ # ---------------------------------------------------------------------------
144
+ # Reward components
145
+ # ---------------------------------------------------------------------------
146
+
147
+
148
+ def format_valid(predicted: str) -> float:
149
+ """1.0 if the predicted text looks like a unified diff; else 0.0.
150
+
151
+ Requires both a ``diff --git`` header and at least one real +/- line
152
+ (not the ``---`` / ``+++`` file-marker lines).
153
+ """
154
+ if not predicted.strip():
155
+ return 0.0
156
+ has_header = False
157
+ has_change = False
158
+ for line in predicted.splitlines():
159
+ if _DIFF_HEADER_RE.match(line):
160
+ has_header = True
161
+ elif (line.startswith("+") or line.startswith("-")) and not line.startswith(
162
+ ("+++ ", "--- ")
163
+ ):
164
+ has_change = True
165
+ if has_header and has_change:
166
+ return 1.0
167
+ return 0.0
168
+
169
+
170
+ def file_targeting(oracle: str, predicted: str) -> float:
171
+ """F1 over the changed-file sets.
172
+
173
+ Why F1 instead of Jaccard:
174
+ - Missing an oracle file (FN) is a *big* failure.
175
+ - Touching one unrelated extra file (FP) is a small one.
176
+ - Jaccard punishes both equally, which over-penalizes the agent
177
+ for any extra exploration.
178
+ - F1 weights TP twice, giving partial credit when the agent finds
179
+ most-but-not-all of the oracle files even with some noise.
180
+
181
+ Returns 1.0 if both sides touch zero files (degenerate).
182
+ """
183
+ o = file_paths(oracle)
184
+ p = file_paths(predicted)
185
+ if not o and not p:
186
+ return 1.0
187
+ tp = len(o & p)
188
+ fn = len(o - p)
189
+ fp = len(p - o)
190
+ if tp == 0:
191
+ return 0.0
192
+ # F1 = 2·TP / (2·TP + FN + FP)
193
+ return (2 * tp) / (2 * tp + fn + fp)
194
+
195
+
196
+ def _count_loc_changes(diff: str) -> int:
197
+ """Number of real +/- lines (excluding file-marker lines)."""
198
+ n = 0
199
+ for line in diff.splitlines():
200
+ if (line.startswith("+") or line.startswith("-")) and not line.startswith(("+++ ", "--- ")):
201
+ n += 1
202
+ return n
203
+
204
+
205
+ def size_sanity(oracle: str, predicted: str) -> float:
206
+ """Penalize predicted patches that are wildly larger / smaller than the oracle.
207
+
208
+ Returns ``min(oracle_loc, predicted_loc) / max(oracle_loc, predicted_loc)``.
209
+ Both empty → 1.0 (degenerate but well-defined). One empty → 0.0.
210
+
211
+ This is the "don't rampage through the codebase" guard — a 200-line
212
+ diff for a 3-line oracle scores ~0.015 here even if every other
213
+ component looks OK.
214
+ """
215
+ o_loc = _count_loc_changes(oracle)
216
+ p_loc = _count_loc_changes(predicted)
217
+ if o_loc == 0 and p_loc == 0:
218
+ return 1.0
219
+ if o_loc == 0 or p_loc == 0:
220
+ return 0.0
221
+ return min(o_loc, p_loc) / max(o_loc, p_loc)
222
+
223
+
224
+ def region_overlap(oracle: str, predicted: str, *, slack_lines: int = 5) -> float:
225
+ """For each oracle hunk, did the predicted diff edit a line within
226
+ ``slack_lines`` of that hunk in the same file?
227
+
228
+ Returns the fraction of oracle hunks that have at least one matching
229
+ predicted hunk. ``slack_lines`` tolerates slight line-number drift
230
+ when git diff renders the predicted hunk at a different offset.
231
+ """
232
+ o_ranges = hunk_ranges(oracle)
233
+ p_ranges = hunk_ranges(predicted)
234
+ total = sum(len(v) for v in o_ranges.values())
235
+ if total == 0:
236
+ return 1.0 # oracle has no hunks (degenerate)
237
+ matched = 0
238
+ for fname, ranges in o_ranges.items():
239
+ p_in_file = p_ranges.get(fname, [])
240
+ for o_start, o_end in ranges:
241
+ for p_start, p_end in p_in_file:
242
+ # Interval overlap with slack — max(starts) <= min(ends) + slack
243
+ if max(o_start, p_start) <= min(o_end, p_end) + slack_lines:
244
+ matched += 1
245
+ break
246
+ return matched / total
247
+
248
+
249
+ def similarity(oracle: str, predicted: str) -> float:
250
+ """SequenceMatcher ratio over +/- lines only.
251
+
252
+ No free credit for context lines — fixes the v0.8.1 inflation where a
253
+ one-line fix scored ~0.7 just because the 3 context lines on either
254
+ side were "matched".
255
+ """
256
+ if not predicted.strip():
257
+ return 0.0
258
+ o = _normalize_changes_only(oracle)
259
+ p = _normalize_changes_only(predicted)
260
+ if not o:
261
+ return 0.0
262
+ # Exact matching is quadratic-or-worse on repeated lines: 200 x 2,000
263
+ # identical changed lines take ~2 s, 500 x 5,000 take ~35 s, which can
264
+ # run the verifier past Harbor's timeout. Above this many line pairs,
265
+ # fall back to difflib's popular-element heuristic, which stays fast.
266
+ exact = len(o) * len(p) <= _SIMILARITY_EXACT_PAIRS
267
+ return difflib.SequenceMatcher(a=o, b=p, autojunk=not exact).ratio()
268
+
269
+
270
+ _SIMILARITY_EXACT_PAIRS = 400_000
271
+
272
+ # A predicted patch over 10x the oracle's changed lines is already a
273
+ # catastrophic size mismatch (size_sanity < 0.10). Past this floor such a
274
+ # patch is a graded 0 instead of being scored, so one huge file can't slow
275
+ # the verifier past its timeout and turn a failing episode into a dropped,
276
+ # ungraded one. The byte cap stops it from being read at all.
277
+ _MAX_PREDICTED_FACTOR = 10
278
+ _MAX_PREDICTED_FLOOR_LOC = 1_000
279
+ _MAX_PREDICTED_BYTES = 16 * 1024 * 1024
280
+
281
+
282
+ def predicted_too_large(oracle: str, predicted: str) -> bool:
283
+ """Whether the predicted patch is too large to score (a graded 0)."""
284
+ limit = max(_MAX_PREDICTED_FACTOR * _count_loc_changes(oracle), _MAX_PREDICTED_FLOOR_LOC)
285
+ return _count_loc_changes(predicted) > limit
286
+
287
+
288
+ # ---------------------------------------------------------------------------
289
+ # LLM-as-judge (Anthropic Messages API, stdlib urllib)
290
+ # ---------------------------------------------------------------------------
291
+
292
+
293
+ _JUDGE_PROMPT = (
294
+ "You are scoring a code-fix patch on whether it logically addresses the "
295
+ "described issue. Output a single JSON object: "
296
+ '{{"score": <float in [0,1]>, "reasoning": "<<=30 words"}}.\n\n'
297
+ "DO NOT use the oracle to grade. Score on:\n"
298
+ " - Does the predicted diff touch code regions that could plausibly fix the issue?\n"
299
+ " - Is the change direction consistent with what the issue describes?\n"
300
+ " - Is it a real attempt (not boilerplate, not no-op)?\n\n"
301
+ "Issue:\n{instruction}\n\n"
302
+ "Oracle (reference fix for comparison only — don't grade on similarity to it):\n"
303
+ "{oracle}\n\n"
304
+ "Predicted:\n{predicted}\n\n"
305
+ "Return ONLY the JSON object."
306
+ )
307
+
308
+
309
+ _DEFAULT_JUDGE_MODEL = "claude-haiku-4-5-20251001"
310
+ _ANTHROPIC_MESSAGES_URL = "https://api.anthropic.com/v1/messages"
311
+ # Bearer token for a self-hosted judge when R2E_JUDGE_API_KEY is unset. vLLM /
312
+ # Ollama ignore it; the OpenAI wire format still wants one. Same value llm.py uses.
313
+ _PLACEHOLDER_API_KEY = "EMPTY"
314
+
315
+
316
+ def llm_judge(
317
+ *,
318
+ instruction: str,
319
+ oracle: str,
320
+ predicted: str,
321
+ api_key: str,
322
+ model: str = _DEFAULT_JUDGE_MODEL,
323
+ timeout: int = 60,
324
+ endpoint: str | None = None,
325
+ ) -> tuple[float | None, str]:
326
+ """Return ``(score, status)``.
327
+
328
+ ``score`` is a float in [0, 1] on success, ``None`` on failure.
329
+ ``status`` is a short string: ``"ok"`` / ``"no_api_key"`` /
330
+ ``"no_judge_model"`` / ``"empty_predicted"`` / ``"network"`` /
331
+ ``"parse"`` / ``"output_limit"`` / ``"missing_score"`` / ``"invalid_score"``.
332
+ ``output_limit`` means the judge exhausted its configured token budget
333
+ (ungraded, even if a partial answer contains a score). ``parse`` means
334
+ the provider's body isn't JSON or has the wrong shape (ungraded); a reply
335
+ with no usable text (refusal, content filter, empty) or no valid score is
336
+ ``missing_score`` / ``invalid_score`` (a graded 0). A missing score never
337
+ increases the other weights.
338
+
339
+ ``endpoint`` — base URL of an OpenAI-compatible server. When set, the
340
+ request goes to ``<endpoint>/chat/completions`` with ``api_key`` as a
341
+ bearer token, at temperature 0, and ``model`` must be given explicitly;
342
+ otherwise it goes to Anthropic's Messages API unchanged.
343
+ """
344
+ if not api_key:
345
+ return None, "no_api_key"
346
+ if endpoint and not model:
347
+ return None, "no_judge_model"
348
+ if not predicted.strip():
349
+ return 0.0, "empty_predicted"
350
+
351
+ # Truncate hard so we don't blow up the prompt for big diffs
352
+ prompt = _JUDGE_PROMPT.format(
353
+ instruction=instruction[:4000],
354
+ oracle=oracle[:4000],
355
+ predicted=predicted[:4000],
356
+ )
357
+ payload: dict = {
358
+ "model": model,
359
+ "max_tokens": 200,
360
+ "messages": [{"role": "user", "content": prompt}],
361
+ }
362
+ if endpoint:
363
+ # Small self-hosted models are noisy judges at their default sampling
364
+ # temperature (same input scoring 0.0 one call and 1.0 the next); pin
365
+ # them to greedy. The Anthropic route keeps its defaults — the weights
366
+ # were calibrated against them.
367
+ payload["temperature"] = 0
368
+ url = endpoint.rstrip("/") + "/chat/completions"
369
+ headers = {
370
+ "authorization": f"Bearer {api_key}",
371
+ "content-type": "application/json",
372
+ }
373
+ else:
374
+ url = _ANTHROPIC_MESSAGES_URL
375
+ headers = {
376
+ "x-api-key": api_key,
377
+ "anthropic-version": "2023-06-01",
378
+ "content-type": "application/json",
379
+ }
380
+ body = json.dumps(payload).encode("utf-8")
381
+ req = urllib.request.Request(url, data=body, headers=headers, method="POST")
382
+ try:
383
+ with urllib.request.urlopen(req, timeout=timeout) as resp:
384
+ raw = resp.read().decode("utf-8")
385
+ except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError, OSError):
386
+ return None, "network"
387
+
388
+ try:
389
+ response = json.loads(raw)
390
+ except json.JSONDecodeError:
391
+ return None, "parse"
392
+ # Provider-reported truncation is a grader capacity failure, not evidence
393
+ # that the submitted patch is wrong. Reasoning models can spend the entire
394
+ # output budget before producing visible text. Never grade a partial score.
395
+ if isinstance(response, dict):
396
+ choices = response.get("choices")
397
+ if endpoint:
398
+ if (
399
+ isinstance(choices, list)
400
+ and choices
401
+ and isinstance(choices[0], dict)
402
+ and choices[0].get("finish_reason") == "length"
403
+ ):
404
+ return None, "output_limit"
405
+ elif response.get("stop_reason") in {"max_tokens", "model_context_window_exceeded"}:
406
+ return None, "output_limit"
407
+ text = _judge_text(response, openai_compatible=bool(endpoint))
408
+ if text is None:
409
+ return None, "parse"
410
+
411
+ # Pull the first JSON object out of the model's response
412
+ m = re.search(r"\{[^{}]*\"score\"[^{}]*\}", text, re.DOTALL)
413
+ if not m:
414
+ return None, "missing_score"
415
+ try:
416
+ obj = json.loads(m.group(0))
417
+ score = obj.get("score")
418
+ except (json.JSONDecodeError, ValueError, TypeError):
419
+ return None, "missing_score"
420
+ if type(score) not in (int, float) or not 0 <= score <= 1 or not math.isfinite(score):
421
+ return None, "invalid_score"
422
+ return float(score), "ok"
423
+
424
+
425
+ def _judge_text(payload: object, *, openai_compatible: bool) -> str | None:
426
+ """The judge's answer text, ``""`` when it gave none, ``None`` for a wrong shape.
427
+
428
+ A refusal or a content filter is a well-formed reply with no usable text.
429
+ The agent's patch is in the prompt, so it can provoke one: that is ``""``,
430
+ which grades 0, not ``None``, which leaves the run ungraded.
431
+
432
+ Anthropic: a refusal is HTTP 200 with ``stop_reason: "refusal"`` and
433
+ ``content`` empty or holding partial text to discard. OpenAI-compatible:
434
+ ``message.content`` is null with a ``refusal`` string or
435
+ ``finish_reason: "content_filter"``.
436
+ """
437
+ if not isinstance(payload, dict):
438
+ return None
439
+ if openai_compatible:
440
+ choices = payload.get("choices")
441
+ if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
442
+ return None
443
+ message = choices[0].get("message")
444
+ if not isinstance(message, dict):
445
+ return None
446
+ if message.get("refusal") or choices[0].get("finish_reason") == "content_filter":
447
+ return ""
448
+ content = message.get("content")
449
+ if content is None:
450
+ return ""
451
+ if isinstance(content, str):
452
+ return content
453
+ if isinstance(content, list): # content parts
454
+ return "".join(
455
+ part.get("text", "")
456
+ for part in content
457
+ if isinstance(part, dict) and isinstance(part.get("text", ""), str)
458
+ )
459
+ return None
460
+ content = payload.get("content")
461
+ if not isinstance(content, list):
462
+ return None
463
+ if payload.get("stop_reason") == "refusal":
464
+ return ""
465
+ return "".join(
466
+ block["text"]
467
+ for block in content
468
+ if isinstance(block, dict)
469
+ and block.get("type", "text") == "text"
470
+ and isinstance(block.get("text"), str)
471
+ )
472
+
473
+
474
+ # ---------------------------------------------------------------------------
475
+ # Combination
476
+ # ---------------------------------------------------------------------------
477
+
478
+
479
+ # Judge replies the agent can provoke: its patch text is part of the judge
480
+ # prompt, so it can steer the answer away from a valid score. These are a
481
+ # graded 0. An unreadable provider envelope (`parse`), missing configuration,
482
+ # a disabled judge, transport errors and an exhausted judge output budget leave
483
+ # the evaluation ungraded. Truncation alone cannot establish an incorrect patch.
484
+ _JUDGE_GRADED_ZERO = frozenset({"missing_score", "invalid_score"})
485
+
486
+
487
+ def evaluation_status(judge_score: float | None, judge_status: str) -> str:
488
+ """`graded` when the judge scored or the agent can have caused its failure."""
489
+ if judge_score is not None or judge_status in _JUDGE_GRADED_ZERO:
490
+ return "graded"
491
+ return "ungraded"
492
+
493
+
494
+ def combine(components: dict[str, float | None], weights: dict[str, float]) -> float:
495
+ """Combine declared components, requiring a positively weighted judge.
496
+
497
+ Without a judge score the result is 0. ``main`` records it as a graded 0
498
+ when the agent can have caused the judge failure, and otherwise writes no
499
+ reward file, so Harbor reports the trial as VERIFIER_FAILED.
500
+ """
501
+ if weights.get("llm_judge", 0) <= 0 or components.get("llm_judge") is None:
502
+ return 0.0
503
+ if any(w > 0 and components.get(k) is None for k, w in weights.items()):
504
+ return 0.0
505
+ return _weighted_mean(components, weights)
506
+
507
+
508
+ def _weighted_mean(components: dict[str, float | None], weights: dict[str, float]) -> float:
509
+ available = [(k, w) for k, w in weights.items() if w > 0 and components.get(k) is not None]
510
+ if not available:
511
+ return 0.0
512
+ # Relative weights need not sum to one. Scale first so large finite
513
+ # overrides cannot overflow the numerator or denominator into NaN.
514
+ scale = max(w for _, w in available)
515
+ normalized = [(k, w / scale) for k, w in available]
516
+ return sum(w * components[k] for k, w in normalized) / sum(w for _, w in normalized)
517
+
518
+
519
+ # ---------------------------------------------------------------------------
520
+ # Entry point (invoked by tests/test.sh inside the container)
521
+ # ---------------------------------------------------------------------------
522
+
523
+
524
+ # Weights retuned after a 23-task pilot. Rationale (LLM-as-reward-engineer
525
+ # analysis grounded in per-task component data):
526
+ #
527
+ # - format_valid → 0.00: was 1.0 across ALL 21 evaluated tasks. Zero
528
+ # discriminative signal — its 0.05 weight was pure dead weight.
529
+ # - similarity → 0.10: Pearson ~0.85 correlation with region_overlap.
530
+ # Carrying both at 0.20 double-counts positional accuracy and
531
+ # additionally penalizes legitimate alternative implementations.
532
+ # - llm_judge → 0.50: only component capturing semantic correctness
533
+ # independent of textual form; diverges informatively from
534
+ # similarity on cases like tokenizers (judge=0.72, sim=0.08).
535
+ # - region_overlap stays 0.20: strongest spatial-localization signal.
536
+ # - file_targeting → 0.12: leading indicator, less correlated with the
537
+ # rest than region/similarity are with each other.
538
+ # - size_sanity → 0.08: useful outlier detector for catastrophic
539
+ # over/under-generation (prettier=0.01, serde=0.08).
540
+ #
541
+ # Total: 0.00 + 0.08 + 0.12 + 0.20 + 0.10 + 0.50 = 1.00.
542
+ _DEFAULT_WEIGHTS = {
543
+ "format_valid": 0.00,
544
+ "size_sanity": 0.08,
545
+ "file_targeting": 0.12,
546
+ "region_overlap": 0.20,
547
+ "similarity": 0.10,
548
+ "llm_judge": 0.50,
549
+ }
550
+
551
+ # Hard cap: when size_sanity < this threshold, clamp final reward to
552
+ # ≤ CATASTROPHIC_SIZE_CAP. Prevents a charitable judge from inflating
553
+ # the score on patches that are wildly the wrong size (catastrophic
554
+ # over- or under-generation).
555
+ _CATASTROPHIC_SIZE_THRESHOLD = 0.10
556
+ _CATASTROPHIC_SIZE_CAP = 0.40
557
+
558
+
559
+ def _read_weights_from_env() -> dict[str, float]:
560
+ """Override defaults via R2E_W_* env vars (set in container by harbor)."""
561
+ overrides = {
562
+ "format_valid": os.environ.get("R2E_W_FORMAT"),
563
+ "size_sanity": os.environ.get("R2E_W_SIZE"),
564
+ "file_targeting": os.environ.get("R2E_W_FILE"),
565
+ "region_overlap": os.environ.get("R2E_W_REGION"),
566
+ "similarity": os.environ.get("R2E_W_SIM"),
567
+ "llm_judge": os.environ.get("R2E_W_JUDGE"),
568
+ }
569
+ out = dict(_DEFAULT_WEIGHTS)
570
+ for k, v in overrides.items():
571
+ if v is None:
572
+ continue
573
+ try:
574
+ value = float(v)
575
+ if math.isfinite(value) and value >= 0:
576
+ out[k] = value
577
+ except (TypeError, ValueError):
578
+ continue
579
+ return out
580
+
581
+
582
+ def _judge_config_from_env() -> tuple[str, str, str | None]:
583
+ """``(api_key, model, endpoint)`` for the judge, from the verifier env.
584
+
585
+ With ``R2E_JUDGE_ENDPOINT`` set, the key comes from ``R2E_JUDGE_API_KEY``
586
+ (placeholder when unset) and ``ANTHROPIC_API_KEY`` is never forwarded to
587
+ the custom server. ``R2E_JUDGE_MODEL`` has no default on that route (a
588
+ self-hosted server won't have Haiku): when unset, ``model`` comes back
589
+ as ``""`` and ``llm_judge`` reports ``no_judge_model`` instead of
590
+ calling out. Without an endpoint the default Anthropic route is
591
+ unchanged.
592
+ """
593
+ endpoint = os.environ.get("R2E_JUDGE_ENDPOINT", "").strip() or None
594
+ model = os.environ.get("R2E_JUDGE_MODEL", "").strip()
595
+ if endpoint:
596
+ api_key = os.environ.get("R2E_JUDGE_API_KEY", "").strip() or _PLACEHOLDER_API_KEY
597
+ return api_key, model, endpoint
598
+ return os.environ.get("ANTHROPIC_API_KEY", "").strip(), model or _DEFAULT_JUDGE_MODEL, None
599
+
600
+
601
+ def main(argv: list[str] | None = None) -> int:
602
+ parser = argparse.ArgumentParser(description=__doc__)
603
+ parser.add_argument("oracle")
604
+ parser.add_argument("predicted")
605
+ parser.add_argument("instruction")
606
+ parser.add_argument("--out-dir", default="/logs/verifier")
607
+ args = parser.parse_args(argv)
608
+ os.makedirs(args.out_dir, exist_ok=True)
609
+ # This run is the only authority on the reward: an earlier or planted
610
+ # reward file must not stand if this evaluation ends up ungraded.
611
+ for name in ("reward.txt", "reward.json"):
612
+ try:
613
+ os.unlink(os.path.join(args.out_dir, name))
614
+ except FileNotFoundError:
615
+ pass
616
+ oracle = _read_or_empty(args.oracle)
617
+ try:
618
+ oversized = os.path.getsize(args.predicted) > _MAX_PREDICTED_BYTES
619
+ except OSError:
620
+ oversized = False
621
+ predicted = "" if oversized else _read_or_empty(args.predicted)
622
+ if oversized or predicted_too_large(oracle, predicted):
623
+ breakdown = {
624
+ "final_reward": 0.0,
625
+ "evaluation_status": "graded",
626
+ "eval_trustworthy": False,
627
+ "predicted_status": "predicted_too_large",
628
+ }
629
+ _write_outputs(args.out_dir, 0.0, breakdown)
630
+ return 0
631
+ instruction = _read_or_empty(args.instruction)
632
+ api_key, judge_model, judge_endpoint = _judge_config_from_env()
633
+
634
+ fv = format_valid(predicted)
635
+ ss = size_sanity(oracle, predicted)
636
+ ft = file_targeting(oracle, predicted)
637
+ ro = region_overlap(oracle, predicted)
638
+ sim = similarity(oracle, predicted)
639
+ weights = _read_weights_from_env()
640
+ if weights["llm_judge"] <= 0:
641
+ judge_score, judge_status = None, "disabled"
642
+ else:
643
+ judge_score, judge_status = llm_judge(
644
+ instruction=instruction,
645
+ oracle=oracle,
646
+ predicted=predicted,
647
+ api_key=api_key,
648
+ model=judge_model,
649
+ endpoint=judge_endpoint,
650
+ )
651
+
652
+ components: dict[str, float | None] = {
653
+ "format_valid": fv,
654
+ "size_sanity": ss,
655
+ "file_targeting": ft,
656
+ "region_overlap": ro,
657
+ "similarity": sim,
658
+ "llm_judge": judge_score,
659
+ }
660
+ final = combine(components, weights)
661
+ final = max(0.0, min(1.0, final))
662
+
663
+ # Hard cap on catastrophic size mismatches. Without this, a charitable
664
+ # judge can inflate the reward on patches that are dramatically the
665
+ # wrong size (prettier scored 0.23 with size_sanity=0.011 — the judge
666
+ # was lenient at 0.25 despite the patch being a near-no-op vs a
667
+ # 500-line oracle). The cap kicks in only at the extremes.
668
+ if ss < _CATASTROPHIC_SIZE_THRESHOLD:
669
+ final = min(final, _CATASTROPHIC_SIZE_CAP)
670
+
671
+ status = evaluation_status(judge_score, judge_status)
672
+ breakdown = {
673
+ # No reward exists for an ungraded evaluation: null, not a placeholder 0.
674
+ "final_reward": round(final, 6) if status == "graded" else None,
675
+ "evaluation_status": status,
676
+ "eval_trustworthy": judge_score is not None,
677
+ "diagnostic_similarity": round(
678
+ _weighted_mean(components, {k: w for k, w in weights.items() if k != "llm_judge"}),
679
+ 6,
680
+ ),
681
+ "components": {k: (None if v is None else round(v, 6)) for k, v in components.items()},
682
+ "weights": {k: round(v, 6) for k, v in weights.items()},
683
+ "judge_model": judge_model if judge_status == "ok" else None,
684
+ "judge_endpoint": judge_endpoint,
685
+ "judge_status": judge_status,
686
+ }
687
+
688
+ _write_outputs(args.out_dir, final, breakdown)
689
+ return 0
690
+
691
+
692
+ def _write_outputs(out_dir: str, final: float, breakdown: dict) -> None:
693
+ # An ungraded evaluation writes no reward file. Harbor then raises
694
+ # RewardFileNotFoundError: the trial is VERIFIER_FAILED, reward_valid is
695
+ # false, and RL consumers (OpenEnv harbor_env -> TRL) drop the rollout
696
+ # instead of training on a 0. Harbor's job mean and pass@k still count the
697
+ # trial as 0, so evaluation stays fail-closed.
698
+ if breakdown["evaluation_status"] == "graded":
699
+ with open(os.path.join(out_dir, "reward.txt"), "w", encoding="utf-8") as f:
700
+ f.write(f"{final:.6f}\n")
701
+ # Harbor's `reward.json` must be a flat map of floats/ints (spec, see
702
+ # <https://harborframework.com/docs/tasks>); our breakdown carries nested
703
+ # dicts, judge strings, and status strings, so it goes to the sidecar the
704
+ # Harbor UI renders under Verifier Logs → Rewards. Mirrors #75 (Neubig)
705
+ # for `_pr_runtime_verifier.py`.
706
+ with open(os.path.join(out_dir, "reward-details.json"), "w", encoding="utf-8") as f:
707
+ json.dump(breakdown, f, indent=2)
708
+
709
+ # Also print to stdout so harbor's log captures the breakdown
710
+ print(json.dumps(breakdown, indent=2))
711
+
712
+
713
+ def _read_or_empty(path: str) -> str:
714
+ try:
715
+ with open(path, encoding="utf-8") as f:
716
+ return f.read()
717
+ except (OSError, UnicodeDecodeError):
718
+ return ""
719
+
720
+
721
+ if __name__ == "__main__":
722
+ sys.exit(main())
723
+
724
+
725
+ __all__ = [
726
+ "combine",
727
+ "file_paths",
728
+ "file_targeting",
729
+ "format_valid",
730
+ "hunk_ranges",
731
+ "llm_judge",
732
+ "main",
733
+ "predicted_too_large",
734
+ "region_overlap",
735
+ "similarity",
736
+ "size_sanity",
737
+ ]
tasks/livewire__livewire-10633/environment/Dockerfile ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Auto-generated by Repo2RLEnv pr_diff — 6-component reward env.
2
+ # Agent-agnostic: the agent (claude-code / openhands / codex / etc.)
3
+ # installs itself at run time via its harbor adapter. We only ship
4
+ # the source repo — the oracle + verifier arrive at verify time via
5
+ # tests/, never baked into the agent's image.
6
+ FROM python:3.12-slim
7
+ ARG GITHUB_TOKEN=
8
+ RUN apt-get update \
9
+ && apt-get install -y --no-install-recommends git ca-certificates curl \
10
+ && rm -rf /var/lib/apt/lists/*
11
+ RUN git config --global --add safe.directory /workspace \
12
+ && git config --global init.defaultBranch main \
13
+ && git config --global advice.detachedHead false
14
+ RUN if [ -n "$GITHUB_TOKEN" ]; then \
15
+ git clone --filter=blob:none https://x-access-token:"${GITHUB_TOKEN}"@github.com/livewire/livewire.git /workspace; \
16
+ else \
17
+ git clone --filter=blob:none https://github.com/livewire/livewire.git /workspace; \
18
+ fi \
19
+ && git -C /workspace remote set-url origin https://github.com/livewire/livewire.git
20
+ WORKDIR /workspace
21
+ RUN git fetch --depth 1 origin a3064d59dd5f6f5db2f7f81de78948e91551dfe7 2>/dev/null \
22
+ || git fetch --unshallow origin 2>/dev/null || true
23
+ RUN git reset --hard a3064d59dd5f6f5db2f7f81de78948e91551dfe7 \
24
+ && git clean -fdx -e .venv -e venv -e __pycache__
25
+ RUN git checkout -q -B base a3064d59dd5f6f5db2f7f81de78948e91551dfe7 \
26
+ && git remote remove origin 2>/dev/null || true
27
+ RUN for ref in $(git branch --format='%(refname:short)' | grep -vx base); do git branch -D "$ref" 2>/dev/null || true; done \
28
+ && git tag -l | xargs -r git tag -d >/dev/null 2>&1 || true \
29
+ && git for-each-ref --format='%(refname)' refs/remotes 2>/dev/null | xargs -r -n1 git update-ref -d 2>/dev/null || true \
30
+ && git reflog expire --expire=now --all 2>/dev/null || true \
31
+ && git gc --prune=now 2>/dev/null || true
32
+ RUN P="$(git rev-parse --git-dir)/objects/pack"; if ls "$P"/*.promisor >/dev/null 2>&1; then \
33
+ git rev-list --objects --all --missing=allow-promisor > "$P/../scrub.list" \
34
+ && K=$(git pack-objects -q --missing=allow-promisor "$P/scrub" < "$P/../scrub.list") \
35
+ && rm -f "$P/../scrub.list" "$P"/pack-* "$P"/multi-pack-index* \
36
+ && touch "$P/scrub-$K.promisor" && git prune --expire=now; \
37
+ fi
tasks/livewire__livewire-10633/instruction.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** [4.x] Reuse resolved models across properties to avoid duplicate queries on update requests
4
+
5
+ ## Description
6
+
7
+ # The Scenario
8
+
9
+ #9935 stopped `ModelSynth` from re-querying models already resolved by route binding — but that's the only reuse that exists. Every other Eloquent property still hydrates on its own, so a component holding the same model in two places queries it twice on every update request:
10
+
11
+ ```php
12
+ class UserManager extends Component
13
+ {
14
+ public Collection $users;
15
+
16
+ public User $selected;
17
+
18
+ public function mount()
19
+ {
20
+ $this->users = User::query()->limit(3)->get();
21
+ $this->selected = $this->users->first();
22
+ }
23
+ }
24
+ ```
25
+
26
+ Every `$refresh`:
27
+
28
+ | Source | Query |
29
+ |---|---|
30
+ | `EloquentCollectionSynth` | `select * from "users" where "users"."id" in (1, 2, 3)` |
31
+ | `ModelSynth` | `select * from "users" where "users"."id" = 1 limit 1` |
32
+
33
+ The same row is fetched twice because the two synths have no shared state.
34
+
35
+ # The Solution
36
+
37
+ Models resolved during a request are now remembered in a request-scoped store on `SupportModels` (flushed on `flush-state`, same lifecycle as `PersistentMiddleware::$resolvedRouteModels`):
38
+
39
+ * `ModelSynth` checks the store before querying — eagerly at hydration, and again inside the lazy proxy at resolution time (by then a collection may have resolved the model). Freshly queried models are remembered.
40
+ * `EloquentCollectionSynth` reuses every model already in the store and runs its restoration query only for the missing keys (order, duplicates, and dropped-missing-model semantics are unchanged).
41
+ * The route-bound model lookup from #9935 is absorbed as the store's fallback, so collections now reuse route-bound models too, and `ModelSynth` goes through one code path.
42
+
43
+ The repro above drops from 2 queries to 1. Components repeated across a page (or parent/child components sharing the same model) stop issuing one identical query per component payload.
44
+
45
+ ## Only clean instances are reused
46
+
47
+ An instance is only reused while it's indistinguishable from what a fresh query would return. If an instance has been deleted or mutated (`!exists`, `isDirty()`, or `wasChanged()`), the model goes stale for the remainder of the request: nothing reuses it, nothing re-remembers it, and every consumer falls back to today's per-property fresh query. This keeps unsaved mutations in one component from leaking into a sibling component in a pooled update request, and keeps a model deleted mid-request from being resurrected from the store.
48
+
49
+ ## Semantics worth calling out
50
+
51
+ * **Instance sharing**: a model property and "its" row inside a collection can now be the same instance within a request — which is already true at mount time (`$this->selected = $this->users->first()`), for duplicate keys within one collection, and for route-bound models since #9935. Pinned by `test_reused_model_instances_are_shared_within_a_request`.
52
+ * **User-land queries are untouched**: a `#[Computed]` that runs `User::query()->get()` still runs its query every request — intercepting arbitrary Eloquent results (e.g. via a `retrieved` listener) would poison the store with partial `select()` models, so the store only ever holds full `newQueryForRestoration()` instances. The guidance for that shape remains storing a `$selectedId` and looking it up in the computed, or `#[Computed(persist: true)]`.
53
+ * **PHP < 8.4**: without lazy proxies, properties hydrate eagerly in declaration order, so the store dedupes in that order and instances are shared before actions run (the mutation guards can't apply retroactively). CI covers 8.4/8.5; the guard tests skip below 8.4.
54
+ * `retrieved` model events fire once per row instead of once per property — same trade #9935 made.
55
+
56
+ # Tests
57
+
58
+ Nine new unit tests: reuse in both directions (collection→model and model→collection with a narrowed `whereIn`), same-key model properties sharing one query, the zero-query path when a collection is fully resolvable from the store (including duplicate keys), instance-sharing semantics, the dirty/saved/deleted guards (including the reject-then-save sequence that would serve stale data without the stale-tracking), and per-request store flushing. The reuse tests fail on `main`; the full Unit suite and the `SupportModels` browser tests pass.
59
+
60
+ 🤖 Generated with [Claude Code](https://claude.com/claude-code)
61
+
62
+ https://claude.ai/code/session_01XZqLY9MPvjWoG9Y9ygTfsx
63
+
64
+ ## Task
65
+
66
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a3064d59dd5f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/livewire__livewire-10633/solution/patch.diff ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/src/Features/SupportModels/EloquentCollectionSynth.php b/src/Features/SupportModels/EloquentCollectionSynth.php
2
+ index 18bdfa2b..732214b3 100644
3
+ --- a/src/Features/SupportModels/EloquentCollectionSynth.php
4
+ +++ b/src/Features/SupportModels/EloquentCollectionSynth.php
5
+ @@ -76,16 +76,36 @@ class EloquentCollectionSynth extends Synth {
6
+ }
7
+
8
+ return $this->makeLazyProxy($class, $meta, function () use ($modelClass, $keys, $meta) {
9
+ - // We are using Laravel's method here for restoring the collection, which ensures
10
+ - // that all models in the collection are restored in one query, preventing n+1
11
+ - // issues and also only restores models that exist.
12
+ - $collection = (new $modelClass)->newQueryForRestoration($keys)->useWritePdo()->get();
13
+ -
14
+ - $collection = $collection->keyBy->getKey();
15
+ + $models = [];
16
+ + $missingKeys = [];
17
+ +
18
+ + // Reuse any models already resolved this request — by route binding (via
19
+ + // SubstituteBindings middleware) or by another hydrated property — so
20
+ + // that only the remaining models need to be queried.
21
+ + foreach (array_unique($keys) as $key) {
22
+ + if ($model = SupportModels::getResolvedModel($modelClass, $key)) {
23
+ + $models[$key] = $model;
24
+ + } else {
25
+ + $missingKeys[] = $key;
26
+ + }
27
+ + }
28
+ +
29
+ + if (count($missingKeys) > 0) {
30
+ + // We are using Laravel's method here for restoring the collection, which ensures
31
+ + // that all models in the collection are restored in one query, preventing n+1
32
+ + // issues and also only restores models that exist.
33
+ + $collection = (new $modelClass)->newQueryForRestoration($missingKeys)->useWritePdo()->get();
34
+ +
35
+ + foreach ($collection as $model) {
36
+ + $models[$model->getKey()] = $model;
37
+ +
38
+ + SupportModels::rememberResolvedModel($model);
39
+ + }
40
+ + }
41
+
42
+ return new $meta['class'](
43
+ - collect($meta['keys'])->map(function ($id) use ($collection) {
44
+ - return $collection[$id] ?? null;
45
+ + collect($meta['keys'])->map(function ($id) use ($models) {
46
+ + return $models[$id] ?? null;
47
+ })->filter()
48
+ );
49
+ });
50
+ diff --git a/src/Features/SupportModels/ModelSynth.php b/src/Features/SupportModels/ModelSynth.php
51
+ index 0232d750..6d92cc45 100644
52
+ --- a/src/Features/SupportModels/ModelSynth.php
53
+ +++ b/src/Features/SupportModels/ModelSynth.php
54
+ @@ -4,7 +4,6 @@ namespace Livewire\Features\SupportModels;
55
+
56
+ use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth;
57
+ use Livewire\Mechanisms\HandleComponents\ComponentContext;
58
+ -use Livewire\Mechanisms\PersistentMiddleware\PersistentMiddleware;
59
+ use Illuminate\Queue\SerializesAndRestoresModelIdentifiers;
60
+ use Illuminate\Database\Eloquent\Relations\Relation;
61
+ use Illuminate\Database\Eloquent\Model;
62
+ @@ -74,16 +73,29 @@ class ModelSynth extends Synth {
63
+
64
+ $key = $meta['key'];
65
+
66
+ - // If this model was already resolved by route binding (via
67
+ - // SubstituteBindings middleware), reuse it to avoid a duplicate query.
68
+ - $resolvedModel = app(PersistentMiddleware::class)->getResolvedRouteModel($class, $key);
69
+ + // If this model was already resolved this request — by route binding (via
70
+ + // SubstituteBindings middleware) or by another hydrated property — then
71
+ + // reuse it to avoid a duplicate query.
72
+ + $resolvedModel = SupportModels::getResolvedModel($class, $key);
73
+
74
+ if ($resolvedModel) {
75
+ return $resolvedModel;
76
+ }
77
+
78
+ return $this->makeLazyProxy($class, $meta, function () use ($class, $key) {
79
+ - return (new $class)->newQueryForRestoration($key)->useWritePdo()->firstOrFail();
80
+ + // Another property (like a collection containing this model) may have
81
+ + // resolved since hydration, so check for a match one more time...
82
+ + $resolvedModel = SupportModels::getResolvedModel($class, $key);
83
+ +
84
+ + if ($resolvedModel) {
85
+ + return $resolvedModel;
86
+ + }
87
+ +
88
+ + $model = (new $class)->newQueryForRestoration($key)->useWritePdo()->firstOrFail();
89
+ +
90
+ + SupportModels::rememberResolvedModel($model);
91
+ +
92
+ + return $model;
93
+ });
94
+ }
95
+
96
+ diff --git a/src/Features/SupportModels/SupportModels.php b/src/Features/SupportModels/SupportModels.php
97
+ index 7a8b1691..afc9e89c 100644
98
+ --- a/src/Features/SupportModels/SupportModels.php
99
+ +++ b/src/Features/SupportModels/SupportModels.php
100
+ @@ -2,15 +2,62 @@
101
+
102
+ namespace Livewire\Features\SupportModels;
103
+
104
+ +use function Livewire\on;
105
+ +use Livewire\Mechanisms\PersistentMiddleware\PersistentMiddleware;
106
+ use Livewire\ComponentHook;
107
+
108
+ class SupportModels extends ComponentHook
109
+ {
110
+ + public static $resolvedModels = [];
111
+ +
112
+ + public static $staleModels = [];
113
+ +
114
+ static function provide()
115
+ {
116
+ app('livewire')->propertySynthesizer([
117
+ ModelSynth::class,
118
+ EloquentCollectionSynth::class,
119
+ ]);
120
+ +
121
+ + on('flush-state', function () {
122
+ + static::$resolvedModels = [];
123
+ + static::$staleModels = [];
124
+ + });
125
+ + }
126
+ +
127
+ + static function rememberResolvedModel($model)
128
+ + {
129
+ + $hash = get_class($model).':'.$model->getKey();
130
+ +
131
+ + // Don't track models that have gone stale, otherwise a deletion or an
132
+ + // update made through the original instance couldn't be detected...
133
+ + if (isset(static::$staleModels[$hash])) return;
134
+ +
135
+ + static::$resolvedModels[$hash] = $model;
136
+ + }
137
+ +
138
+ + static function getResolvedModel($class, $key)
139
+ + {
140
+ + $hash = $class.':'.$key;
141
+ +
142
+ + if (isset(static::$staleModels[$hash])) return null;
143
+ +
144
+ + $model = static::$resolvedModels[$hash]
145
+ + ?? app(PersistentMiddleware::class)->getResolvedRouteModel($class, $key);
146
+ +
147
+ + if (! $model) return null;
148
+ +
149
+ + // Only reuse an instance that is indistinguishable from a freshly queried
150
+ + // one. Once an instance has been deleted or mutated, stop sharing that
151
+ + // model for the rest of the request and fall back to fresh queries...
152
+ + if (! $model->exists || $model->isDirty() || $model->wasChanged()) {
153
+ + static::$staleModels[$hash] = true;
154
+ +
155
+ + unset(static::$resolvedModels[$hash]);
156
+ +
157
+ + return null;
158
+ + }
159
+ +
160
+ + return $model;
161
+ }
162
+ }
163
+ diff --git a/src/Features/SupportModels/UnitTest.php b/src/Features/SupportModels/UnitTest.php
164
+ index 76a9072c..e025938b 100644
165
+ --- a/src/Features/SupportModels/UnitTest.php
166
+ +++ b/src/Features/SupportModels/UnitTest.php
167
+ @@ -325,6 +325,406 @@ class UnitTest extends \Tests\TestCase
168
+ $this->assertCount(1, array_values($articleQueries));
169
+ }
170
+
171
+ + public function test_a_model_property_reuses_a_model_already_hydrated_by_a_collection_property()
172
+ + {
173
+ + $component = Livewire::test(new class extends \Livewire\Component {
174
+ + public Collection $articles;
175
+ +
176
+ + public Article $selected;
177
+ +
178
+ + public function mount() {
179
+ + $this->articles = Article::all();
180
+ + $this->selected = $this->articles->first();
181
+ + }
182
+ +
183
+ + public function render() { return <<<'HTML'
184
+ + <div>
185
+ + @foreach($articles as $article)
186
+ + {{ $article->title.'-'.$loop->index }}
187
+ + @endforeach
188
+ + {{ 'Selected: '.$selected->title }}
189
+ + </div>
190
+ + HTML; }
191
+ + });
192
+ +
193
+ + Article::resolveConnection()->enableQueryLog();
194
+ + Article::resolveConnection()->flushQueryLog();
195
+ +
196
+ + $component->call('$refresh')
197
+ + ->assertSee('First-0')
198
+ + ->assertSee('Second-1')
199
+ + ->assertSee('Selected: First');
200
+ +
201
+ + $this->assertCount(1, Article::resolveConnection()->getQueryLog());
202
+ + }
203
+ +
204
+ + public function test_a_collection_property_only_queries_models_not_already_hydrated_by_a_model_property()
205
+ + {
206
+ + $component = Livewire::test(new class extends \Livewire\Component {
207
+ + public Article $selected;
208
+ +
209
+ + public Collection $articles;
210
+ +
211
+ + public function mount() {
212
+ + $this->selected = Article::first();
213
+ + $this->articles = Article::all();
214
+ + }
215
+ +
216
+ + public function render() { return <<<'HTML'
217
+ + <div>
218
+ + {{ 'Selected: '.$selected->title }}
219
+ + @foreach($articles as $article)
220
+ + {{ $article->title.'-'.$loop->index }}
221
+ + @endforeach
222
+ + </div>
223
+ + HTML; }
224
+ + });
225
+ +
226
+ + Article::resolveConnection()->enableQueryLog();
227
+ + Article::resolveConnection()->flushQueryLog();
228
+ +
229
+ + $component->call('$refresh')
230
+ + ->assertSee('Selected: First')
231
+ + ->assertSee('First-0')
232
+ + ->assertSee('Second-1');
233
+ +
234
+ + $queryLog = Article::resolveConnection()->getQueryLog();
235
+ +
236
+ + $this->assertCount(2, $queryLog);
237
+ +
238
+ + // The collection query should only restore the model that wasn't already
239
+ + // resolved by the model property. Integer keys may be inlined into the
240
+ + // SQL or passed as bindings depending on the Laravel version...
241
+ + [$modelQuery, $collectionQuery] = $queryLog;
242
+ +
243
+ + $this->assertTrue(
244
+ + str_contains($collectionQuery['query'], 'in (2)') || $collectionQuery['bindings'] === [2],
245
+ + 'The collection should only have queried for the unresolved model',
246
+ + );
247
+ + }
248
+ +
249
+ + public function test_two_model_properties_with_the_same_key_are_hydrated_with_one_query()
250
+ + {
251
+ + $component = Livewire::test(new class extends \Livewire\Component {
252
+ + public Article $first;
253
+ +
254
+ + public Article $second;
255
+ +
256
+ + public function mount() {
257
+ + $this->first = Article::first();
258
+ + $this->second = Article::first();
259
+ + }
260
+ +
261
+ + public function render() { return <<<'HTML'
262
+ + <div>{{ 'a:'.$first->title }} {{ 'b:'.$second->title }}</div>
263
+ + HTML; }
264
+ + });
265
+ +
266
+ + Article::resolveConnection()->enableQueryLog();
267
+ + Article::resolveConnection()->flushQueryLog();
268
+ +
269
+ + $component->call('$refresh')
270
+ + ->assertSee('a:First')
271
+ + ->assertSee('b:First');
272
+ +
273
+ + $this->assertCount(1, Article::resolveConnection()->getQueryLog());
274
+ + }
275
+ +
276
+ + public function test_reused_model_instances_are_shared_within_a_request()
277
+ + {
278
+ + Livewire::test(new class extends \Livewire\Component {
279
+ + public Collection $articles;
280
+ +
281
+ + public Article $selected;
282
+ +
283
+ + public function mount() {
284
+ + $this->articles = Article::all();
285
+ + $this->selected = $this->articles->first();
286
+ + }
287
+ +
288
+ + public function rename() {
289
+ + $this->articles->count();
290
+ +
291
+ + $this->selected->title = 'Renamed';
292
+ + }
293
+ +
294
+ + public function render() { return <<<'HTML'
295
+ + <div>
296
+ + @foreach($articles as $article)
297
+ + {{ $article->title.'-'.$loop->index }}
298
+ + @endforeach
299
+ + </div>
300
+ + HTML; }
301
+ + })
302
+ + ->call('rename')
303
+ + ->assertSee('Renamed-0')
304
+ + ->assertSee('Second-1');
305
+ + }
306
+ +
307
+ + public function test_a_collection_is_not_queried_when_all_its_models_are_already_resolved()
308
+ + {
309
+ + $component = Livewire::test(new class extends \Livewire\Component {
310
+ + public Article $one;
311
+ +
312
+ + public Article $two;
313
+ +
314
+ + public Collection $articles;
315
+ +
316
+ + public function mount() {
317
+ + $this->one = Article::find(1);
318
+ + $this->two = Article::find(2);
319
+ + $this->articles = new Collection([Article::find(1), Article::find(1), Article::find(2)]);
320
+ + }
321
+ +
322
+ + public function render() { return <<<'HTML'
323
+ + <div>
324
+ + {{ 'a:'.$one->title }} {{ 'b:'.$two->title }}
325
+ + @foreach($articles as $article)
326
+ + {{ $article->title.'-'.$loop->index }}
327
+ + @endforeach
328
+ + </div>
329
+ + HTML; }
330
+ + });
331
+ +
332
+ + Article::resolveConnection()->enableQueryLog();
333
+ + Article::resolveConnection()->flushQueryLog();
334
+ +
335
+ + $component->call('$refresh')
336
+ + ->assertSee('a:First')
337
+ + ->assertSee('b:Second')
338
+ + ->assertSee('First-0')
339
+ + ->assertSee('First-1')
340
+ + ->assertSee('Second-2');
341
+ +
342
+ + $this->assertCount(2, Article::resolveConnection()->getQueryLog());
343
+ + }
344
+ +
345
+ + public function test_resolved_models_are_not_reused_across_requests()
346
+ + {
347
+ + $component = Livewire::test(new class extends \Livewire\Component {
348
+ + public Article $article;
349
+ +
350
+ + public function mount() {
351
+ + $this->article = Article::first();
352
+ + }
353
+ +
354
+ + public function render() { return <<<'HTML'
355
+ + <div>{{ $article->title }}</div>
356
+ + HTML; }
357
+ + });
358
+ +
359
+ + Article::resolveConnection()->enableQueryLog();
360
+ + Article::resolveConnection()->flushQueryLog();
361
+ +
362
+ + $component->call('$refresh')->assertSee('First');
363
+ + $component->call('$refresh')->assertSee('First');
364
+ +
365
+ + $this->assertCount(2, Article::resolveConnection()->getQueryLog());
366
+ + }
367
+ +
368
+ + public function test_a_mutated_model_is_not_reused_by_other_properties()
369
+ + {
370
+ + // On earlier versions there are no lazy proxies, so properties hydrate
371
+ + // eagerly before any mutations and share the still-clean instance...
372
+ + if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies');
373
+ +
374
+ + $component = Livewire::test(new class extends \Livewire\Component {
375
+ + public Article $first;
376
+ +
377
+ + public Article $second;
378
+ +
379
+ + public function mount() {
380
+ + $this->first = Article::first();
381
+ + $this->second = Article::first();
382
+ + }
383
+ +
384
+ + public function rename() {
385
+ + $this->first->title = 'Draft';
386
+ + }
387
+ +
388
+ + public function render() { return <<<'HTML'
389
+ + <div>{{ 'a:'.$first->title }} {{ 'b:'.$second->title }}</div>
390
+ + HTML; }
391
+ + });
392
+ +
393
+ + Article::resolveConnection()->enableQueryLog();
394
+ + Article::resolveConnection()->flushQueryLog();
395
+ +
396
+ + // The unsaved mutation on $first shouldn't leak into $second — it
397
+ + // should fall through to a fresh query instead...
398
+ + $component->call('rename')
399
+ + ->assertSee('a:Draft')
400
+ + ->assertSee('b:First');
401
+ +
402
+ + $this->assertCount(2, Article::resolveConnection()->getQueryLog());
403
+ + }
404
+ +
405
+ + public function test_a_deleted_model_is_not_reused_when_hydrating_a_collection()
406
+ + {
407
+ + // On earlier versions there are no lazy proxies, so the collection is
408
+ + // hydrated eagerly before the deletion, like it is on main...
409
+ + if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies');
410
+ +
411
+ + $this->resetMutableArticles();
412
+ +
413
+ + Livewire::test(new class extends \Livewire\Component {
414
+ + public Collection $articles;
415
+ +
416
+ + public MutableArticle $selected;
417
+ +
418
+ + public function mount() {
419
+ + $this->articles = MutableArticle::all();
420
+ + $this->selected = $this->articles->first();
421
+ + }
422
+ +
423
+ + public function deleteSelected() {
424
+ + $this->selected->delete();
425
+ + }
426
+ +
427
+ + public function render() { return <<<'HTML'
428
+ + <div>
429
+ + @foreach($articles as $article)
430
+ + {{ $article->title.'-'.$loop->index }}
431
+ + @endforeach
432
+ + </div>
433
+ + HTML; }
434
+ + })
435
+ + ->call('deleteSelected')
436
+ + ->assertDontSee('First-')
437
+ + ->assertSee('Second-0');
438
+ + }
439
+ +
440
+ + public function test_a_saved_model_is_not_reused_by_other_properties()
441
+ + {
442
+ + if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies');
443
+ +
444
+ + $this->resetMutableArticles();
445
+ +
446
+ + $component = Livewire::test(new class extends \Livewire\Component {
447
+ + public MutableArticle $first;
448
+ +
449
+ + public MutableArticle $second;
450
+ +
451
+ + public function mount() {
452
+ + $this->first = MutableArticle::find(1);
453
+ + $this->second = MutableArticle::find(1);
454
+ + }
455
+ +
456
+ + public function rename() {
457
+ + $this->first->update(['title' => 'Renamed']);
458
+ + }
459
+ +
460
+ + public function render() { return <<<'HTML'
461
+ + <div>{{ 'a:'.$first->title }} {{ 'b:'.$second->title }}</div>
462
+ + HTML; }
463
+ + });
464
+ +
465
+ + MutableArticle::resolveConnection()->enableQueryLog();
466
+ + MutableArticle::resolveConnection()->flushQueryLog();
467
+ +
468
+ + // The saved model shouldn't be reused for $second — it should fall
469
+ + // through to a fresh query, which reads the same saved title...
470
+ + $component->call('rename')
471
+ + ->assertSee('a:Renamed')
472
+ + ->assertSee('b:Renamed');
473
+ +
474
+ + $selects = array_filter(
475
+ + MutableArticle::resolveConnection()->getQueryLog(),
476
+ + fn ($q) => str_starts_with($q['query'], 'select'),
477
+ + );
478
+ +
479
+ + $this->assertCount(2, $selects);
480
+ + }
481
+ +
482
+ + public function test_a_model_saved_after_its_reuse_was_rejected_is_not_served_stale()
483
+ + {
484
+ + if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies');
485
+ +
486
+ + $this->resetMutableArticles();
487
+ +
488
+ + Livewire::test(new class extends \Livewire\Component {
489
+ + public MutableArticle $first;
490
+ +
491
+ + public MutableArticle $second;
492
+ +
493
+ + public Collection $articles;
494
+ +
495
+ + public function mount() {
496
+ + $this->first = MutableArticle::find(1);
497
+ + $this->second = MutableArticle::find(1);
498
+ + $this->articles = MutableArticle::all();
499
+ + }
500
+ +
501
+ + public function rename() {
502
+ + // Once a mutated instance is encountered, the model shouldn't be
503
+ + // shared for the rest of the request — even after the collection
504
+ + // resolves a clean instance while the mutation is unsaved...
505
+ + $this->first->title = 'Renamed';
506
+ +
507
+ + $this->articles->count();
508
+ +
509
+ + $this->first->save();
510
+ + }
511
+ +
512
+ + public function render() { return <<<'HTML'
513
+ + <div>{{ 'b:'.$second->title }}</div>
514
+ + HTML; }
515
+ + })
516
+ + ->call('rename')
517
+ + ->assertSee('b:Renamed');
518
+ + }
519
+ +
520
+ + public function test_a_model_deleted_after_its_reuse_was_rejected_is_not_resurrected()
521
+ + {
522
+ + if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies');
523
+ +
524
+ + $this->resetMutableArticles();
525
+ +
526
+ + Livewire::test(new class extends \Livewire\Component {
527
+ + public MutableArticle $selected;
528
+ +
529
+ + public Collection $articles;
530
+ +
531
+ + public Collection $others;
532
+ +
533
+ + public function mount() {
534
+ + $this->selected = MutableArticle::find(1);
535
+ + $this->articles = MutableArticle::all();
536
+ + $this->others = MutableArticle::all();
537
+ + }
538
+ +
539
+ + public function deleteSelected() {
540
+ + $this->selected->title = 'Doomed';
541
+ +
542
+ + $this->articles->count();
543
+ +
544
+ + $this->selected->delete();
545
+ + }
546
+ +
547
+ + public function render() { return <<<'HTML'
548
+ + <div>
549
+ + @foreach($others as $article)
550
+ + {{ $article->title.'-'.$loop->index }}
551
+ + @endforeach
552
+ + </div>
553
+ + HTML; }
554
+ + })
555
+ + ->call('deleteSelected')
556
+ + ->assertDontSee('First-')
557
+ + ->assertDontSee('Doomed-')
558
+ + ->assertSee('Second-0');
559
+ + }
560
+ +
561
+ + protected function resetMutableArticles()
562
+ + {
563
+ + // Reset the table as these tests modify or delete its rows...
564
+ + MutableArticle::query()->delete();
565
+ + MutableArticle::insert([
566
+ + ['id' => 1, 'title' => 'First'],
567
+ + ['id' => 2, 'title' => 'Second'],
568
+ + ]);
569
+ + }
570
+ +
571
+ public function test_hydrating_an_empty_eloquent_collection_does_not_trigger_deprecations()
572
+ {
573
+ $component = Livewire::test(new class extends \Livewire\Component {
574
+ @@ -384,6 +784,19 @@ class Article extends Model
575
+ ];
576
+ }
577
+
578
+ +// Uses its own table so modifying or deleting rows doesn't affect other tests...
579
+ +class MutableArticle extends Model
580
+ +{
581
+ + use Sushi;
582
+ +
583
+ + protected $guarded = [];
584
+ +
585
+ + protected $rows = [
586
+ + ['title' => 'First'],
587
+ + ['title' => 'Second'],
588
+ + ];
589
+ +}
590
+ +
591
+ // Simulates tightenco/parental's HasParent trait, which overrides
592
+ // getTable() and getMorphClass() to return the parent's values so
593
+ // that polymorphic relations use the parent's table.
tasks/livewire__livewire-10633/solution/solve.sh ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ set -euxo pipefail
3
+ cd /workspace
4
+ git config --global --add safe.directory /workspace
5
+ PATCH="$(dirname "$0")/patch.diff"
6
+ git apply --verbose --reject "$PATCH"
tasks/livewire__livewire-10633/task.toml ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version = "1.0"
2
+
3
+ [task]
4
+ name = "trending/livewire__livewire-10633"
5
+ description = "[4.x] Reuse resolved models across properties to avoid duplicate queries on update requests"
6
+
7
+ [metadata]
8
+ difficulty = "large"
9
+ category = "bugfix"
10
+ keywords = [
11
+ "livewire",
12
+ "pr_diff",
13
+ ]
14
+
15
+ [metadata.repo2env]
16
+ pipeline = "pr_diff"
17
+ pipeline_version = "0.3.0"
18
+ repo = "livewire/livewire"
19
+ ref = "a3064d59dd5f6f5db2f7f81de78948e91551dfe7"
20
+ reference = "https://github.com/livewire/livewire/pull/10633"
21
+ source_access = "auto"
22
+ built_at = "2026-11-16T16:09:51.533341+00:00"
23
+ reward_kinds = [
24
+ "diff_similarity",
25
+ ]
26
+ spec_version = "0.2.0"
27
+ content_hash = "sha256:7ae2ef80bbdb222b16707180aa66abb26bccc916f7405870ac11c56638615c36"
28
+
29
+ [metadata.repo2env.pr_diff]
30
+ pr_merged_at = "2026-08-30T12:29:58Z"
31
+ diff_format = "unified"
32
+ context_files = [
33
+ "src/Features/SupportModels/EloquentCollectionSynth.php",
34
+ "src/Features/SupportModels/ModelSynth.php",
35
+ "src/Features/SupportModels/SupportModels.php",
36
+ "src/Features/SupportModels/UnitTest.php",
37
+ ]
38
+ bootstrap_image = "python:3.12-slim"
39
+
40
+ [metadata.repo2env.reward_calibration]
41
+ baseline_reward = 0.0
42
+ loc_changed = 518
43
+ difficulty = "large"
44
+
45
+ [metadata.repo2env.evaluation]
46
+ schema_version = "1"
47
+ status = "unverified"
48
+ stage = "generation"
49
+ reason_codes = [
50
+ "validation_not_run",
51
+ ]
52
+ detail = "Generated task; validation has not been established."
53
+ provenance = "unknown"
54
+ evidence = []
55
+
56
+ [metadata.repo2env.reproducibility]
57
+ mode = "inline_dockerfile"
58
+ image_ref = "python:3.12-slim"
59
+ image_tag = "python:3.12-slim"
60
+ image_visibility = "public"
61
+ pushed_at = "2026-11-16T16:20:01.368381+00:00"
62
+ pushed_by = "scalingX"
63
+ inline_recipe_sha256 = "sha256:bd16521b85539f865b378312637655ca8ab5a3902f455f507e116f27e1d0eac0"
64
+ inline_recipe_lines = 37
65
+ inline_recipe_source = "user_dockerfile"
66
+
67
+ [agent]
68
+ timeout_sec = 1800.0
69
+
70
+ [verifier]
71
+ timeout_sec = 300.0
tasks/livewire__livewire-10633/tests/capture.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Standalone PR-diff capture without executing workspace Git configuration.
2
+
3
+ The emitted task uses a regular clone with a pinned base commit. Only its
4
+ object store is read: refs, index, config, hooks and replacement refs are not
5
+ used. This is a configuration boundary, not a sandbox for a malicious process
6
+ that can modify the verifier, binaries or object store while capture runs.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import argparse
12
+ import json
13
+ import os
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+
22
+ def capture(workspace: Path, base_commit: str) -> bytes:
23
+ """Capture tracked and new files through a fresh private Git index."""
24
+ if not re.fullmatch(r"[a-fA-F0-9]{40}", base_commit):
25
+ raise ValueError("Expected the task's pinned SHA-1 base commit")
26
+ objects = workspace.resolve() / ".git" / "objects"
27
+ if not objects.is_dir():
28
+ raise ValueError("The task's cloned Git object store is missing")
29
+ git = shutil.which("git", path=os.defpath)
30
+ if git is None:
31
+ raise FileNotFoundError("System git is unavailable")
32
+ with tempfile.TemporaryDirectory(prefix="r2e-diff-") as temporary:
33
+ private = Path(temporary)
34
+ # Do not forward GIT_CONFIG_PARAMETERS/COUNT, external diff programs,
35
+ # system/global includes, user attributes, templates or credential env.
36
+ env = {
37
+ "PATH": os.defpath,
38
+ "HOME": temporary,
39
+ "XDG_CONFIG_HOME": temporary,
40
+ "GIT_CONFIG_NOSYSTEM": "1",
41
+ "GIT_CONFIG_GLOBAL": os.devnull,
42
+ "GIT_ATTR_NOSYSTEM": "1",
43
+ "GIT_NO_REPLACE_OBJECTS": "1",
44
+ "GIT_NO_LAZY_FETCH": "1",
45
+ "GIT_TERMINAL_PROMPT": "0",
46
+ "LC_ALL": "C",
47
+ }
48
+ subprocess.run(
49
+ [git, "init", "--quiet", "--template=", str(private / "repository")],
50
+ env=env,
51
+ cwd=private,
52
+ check=True,
53
+ capture_output=True,
54
+ timeout=60,
55
+ )
56
+ env["GIT_ALTERNATE_OBJECT_DIRECTORIES"] = json.dumps(str(objects), ensure_ascii=False)
57
+ command = [
58
+ git,
59
+ f"--git-dir={private / 'repository/.git'}",
60
+ f"--work-tree={workspace.resolve()}",
61
+ ]
62
+
63
+ def run(*args: str) -> bytes:
64
+ return subprocess.run(
65
+ [*command, *args],
66
+ env=env,
67
+ cwd=workspace,
68
+ check=True,
69
+ capture_output=True,
70
+ timeout=60,
71
+ ).stdout
72
+
73
+ run("read-tree", f"{base_commit}^{{tree}}")
74
+ # All filter drivers are undefined in the private configuration. The
75
+ # workspace's clean filters, fsmonitor and hooks cannot be invoked.
76
+ run("add", "--all", "--", ".")
77
+ return run("diff", "--cached", "--no-ext-diff", "--no-textconv", base_commit, "--")
78
+
79
+
80
+ def main(argv: list[str] | None = None) -> int:
81
+ parser = argparse.ArgumentParser(description=__doc__)
82
+ parser.add_argument("workspace", type=Path)
83
+ parser.add_argument("base_commit")
84
+ args = parser.parse_args(argv)
85
+ try:
86
+ patch = capture(args.workspace, args.base_commit)
87
+ except (OSError, ValueError, subprocess.SubprocessError) as exc:
88
+ # Do not echo child stderr: it may contain workspace-controlled data.
89
+ sys.stderr.write(f"PR-diff capture failed ({type(exc).__name__})\n")
90
+ return 1
91
+ sys.stdout.buffer.write(patch)
92
+ return 0
93
+
94
+
95
+ if __name__ == "__main__":
96
+ sys.exit(main())
tasks/livewire__livewire-10633/tests/instruction.md ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Issue
2
+
3
+ **Title:** [4.x] Reuse resolved models across properties to avoid duplicate queries on update requests
4
+
5
+ ## Description
6
+
7
+ # The Scenario
8
+
9
+ #9935 stopped `ModelSynth` from re-querying models already resolved by route binding — but that's the only reuse that exists. Every other Eloquent property still hydrates on its own, so a component holding the same model in two places queries it twice on every update request:
10
+
11
+ ```php
12
+ class UserManager extends Component
13
+ {
14
+ public Collection $users;
15
+
16
+ public User $selected;
17
+
18
+ public function mount()
19
+ {
20
+ $this->users = User::query()->limit(3)->get();
21
+ $this->selected = $this->users->first();
22
+ }
23
+ }
24
+ ```
25
+
26
+ Every `$refresh`:
27
+
28
+ | Source | Query |
29
+ |---|---|
30
+ | `EloquentCollectionSynth` | `select * from "users" where "users"."id" in (1, 2, 3)` |
31
+ | `ModelSynth` | `select * from "users" where "users"."id" = 1 limit 1` |
32
+
33
+ The same row is fetched twice because the two synths have no shared state.
34
+
35
+ # The Solution
36
+
37
+ Models resolved during a request are now remembered in a request-scoped store on `SupportModels` (flushed on `flush-state`, same lifecycle as `PersistentMiddleware::$resolvedRouteModels`):
38
+
39
+ * `ModelSynth` checks the store before querying — eagerly at hydration, and again inside the lazy proxy at resolution time (by then a collection may have resolved the model). Freshly queried models are remembered.
40
+ * `EloquentCollectionSynth` reuses every model already in the store and runs its restoration query only for the missing keys (order, duplicates, and dropped-missing-model semantics are unchanged).
41
+ * The route-bound model lookup from #9935 is absorbed as the store's fallback, so collections now reuse route-bound models too, and `ModelSynth` goes through one code path.
42
+
43
+ The repro above drops from 2 queries to 1. Components repeated across a page (or parent/child components sharing the same model) stop issuing one identical query per component payload.
44
+
45
+ ## Only clean instances are reused
46
+
47
+ An instance is only reused while it's indistinguishable from what a fresh query would return. If an instance has been deleted or mutated (`!exists`, `isDirty()`, or `wasChanged()`), the model goes stale for the remainder of the request: nothing reuses it, nothing re-remembers it, and every consumer falls back to today's per-property fresh query. This keeps unsaved mutations in one component from leaking into a sibling component in a pooled update request, and keeps a model deleted mid-request from being resurrected from the store.
48
+
49
+ ## Semantics worth calling out
50
+
51
+ * **Instance sharing**: a model property and "its" row inside a collection can now be the same instance within a request — which is already true at mount time (`$this->selected = $this->users->first()`), for duplicate keys within one collection, and for route-bound models since #9935. Pinned by `test_reused_model_instances_are_shared_within_a_request`.
52
+ * **User-land queries are untouched**: a `#[Computed]` that runs `User::query()->get()` still runs its query every request — intercepting arbitrary Eloquent results (e.g. via a `retrieved` listener) would poison the store with partial `select()` models, so the store only ever holds full `newQueryForRestoration()` instances. The guidance for that shape remains storing a `$selectedId` and looking it up in the computed, or `#[Computed(persist: true)]`.
53
+ * **PHP < 8.4**: without lazy proxies, properties hydrate eagerly in declaration order, so the store dedupes in that order and instances are shared before actions run (the mutation guards can't apply retroactively). CI covers 8.4/8.5; the guard tests skip below 8.4.
54
+ * `retrieved` model events fire once per row instead of once per property — same trade #9935 made.
55
+
56
+ # Tests
57
+
58
+ Nine new unit tests: reuse in both directions (collection→model and model→collection with a narrowed `whereIn`), same-key model properties sharing one query, the zero-query path when a collection is fully resolvable from the store (including duplicate keys), instance-sharing semantics, the dirty/saved/deleted guards (including the reject-then-save sequence that would serve stale data without the stale-tracking), and per-request store flushing. The reuse tests fail on `main`; the full Unit suite and the `SupportModels` browser tests pass.
59
+
60
+ 🤖 Generated with [Claude Code](https://claude.com/claude-code)
61
+
62
+ https://claude.ai/code/session_01XZqLY9MPvjWoG9Y9ygTfsx
63
+
64
+ ## Task
65
+
66
+ Modify the repository so that the issue described above is resolved. The repository is checked out at base commit `a3064d59dd5f`. Edit files in place; the verifier captures your changes via `git diff` and scores them against an oracle patch using SWE-RL-style diff-similarity reward.
tasks/livewire__livewire-10633/tests/oracle.patch ADDED
@@ -0,0 +1,593 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ diff --git a/src/Features/SupportModels/EloquentCollectionSynth.php b/src/Features/SupportModels/EloquentCollectionSynth.php
2
+ index 18bdfa2b..732214b3 100644
3
+ --- a/src/Features/SupportModels/EloquentCollectionSynth.php
4
+ +++ b/src/Features/SupportModels/EloquentCollectionSynth.php
5
+ @@ -76,16 +76,36 @@ class EloquentCollectionSynth extends Synth {
6
+ }
7
+
8
+ return $this->makeLazyProxy($class, $meta, function () use ($modelClass, $keys, $meta) {
9
+ - // We are using Laravel's method here for restoring the collection, which ensures
10
+ - // that all models in the collection are restored in one query, preventing n+1
11
+ - // issues and also only restores models that exist.
12
+ - $collection = (new $modelClass)->newQueryForRestoration($keys)->useWritePdo()->get();
13
+ -
14
+ - $collection = $collection->keyBy->getKey();
15
+ + $models = [];
16
+ + $missingKeys = [];
17
+ +
18
+ + // Reuse any models already resolved this request — by route binding (via
19
+ + // SubstituteBindings middleware) or by another hydrated property — so
20
+ + // that only the remaining models need to be queried.
21
+ + foreach (array_unique($keys) as $key) {
22
+ + if ($model = SupportModels::getResolvedModel($modelClass, $key)) {
23
+ + $models[$key] = $model;
24
+ + } else {
25
+ + $missingKeys[] = $key;
26
+ + }
27
+ + }
28
+ +
29
+ + if (count($missingKeys) > 0) {
30
+ + // We are using Laravel's method here for restoring the collection, which ensures
31
+ + // that all models in the collection are restored in one query, preventing n+1
32
+ + // issues and also only restores models that exist.
33
+ + $collection = (new $modelClass)->newQueryForRestoration($missingKeys)->useWritePdo()->get();
34
+ +
35
+ + foreach ($collection as $model) {
36
+ + $models[$model->getKey()] = $model;
37
+ +
38
+ + SupportModels::rememberResolvedModel($model);
39
+ + }
40
+ + }
41
+
42
+ return new $meta['class'](
43
+ - collect($meta['keys'])->map(function ($id) use ($collection) {
44
+ - return $collection[$id] ?? null;
45
+ + collect($meta['keys'])->map(function ($id) use ($models) {
46
+ + return $models[$id] ?? null;
47
+ })->filter()
48
+ );
49
+ });
50
+ diff --git a/src/Features/SupportModels/ModelSynth.php b/src/Features/SupportModels/ModelSynth.php
51
+ index 0232d750..6d92cc45 100644
52
+ --- a/src/Features/SupportModels/ModelSynth.php
53
+ +++ b/src/Features/SupportModels/ModelSynth.php
54
+ @@ -4,7 +4,6 @@ namespace Livewire\Features\SupportModels;
55
+
56
+ use Livewire\Mechanisms\HandleComponents\Synthesizers\Synth;
57
+ use Livewire\Mechanisms\HandleComponents\ComponentContext;
58
+ -use Livewire\Mechanisms\PersistentMiddleware\PersistentMiddleware;
59
+ use Illuminate\Queue\SerializesAndRestoresModelIdentifiers;
60
+ use Illuminate\Database\Eloquent\Relations\Relation;
61
+ use Illuminate\Database\Eloquent\Model;
62
+ @@ -74,16 +73,29 @@ class ModelSynth extends Synth {
63
+
64
+ $key = $meta['key'];
65
+
66
+ - // If this model was already resolved by route binding (via
67
+ - // SubstituteBindings middleware), reuse it to avoid a duplicate query.
68
+ - $resolvedModel = app(PersistentMiddleware::class)->getResolvedRouteModel($class, $key);
69
+ + // If this model was already resolved this request — by route binding (via
70
+ + // SubstituteBindings middleware) or by another hydrated property — then
71
+ + // reuse it to avoid a duplicate query.
72
+ + $resolvedModel = SupportModels::getResolvedModel($class, $key);
73
+
74
+ if ($resolvedModel) {
75
+ return $resolvedModel;
76
+ }
77
+
78
+ return $this->makeLazyProxy($class, $meta, function () use ($class, $key) {
79
+ - return (new $class)->newQueryForRestoration($key)->useWritePdo()->firstOrFail();
80
+ + // Another property (like a collection containing this model) may have
81
+ + // resolved since hydration, so check for a match one more time...
82
+ + $resolvedModel = SupportModels::getResolvedModel($class, $key);
83
+ +
84
+ + if ($resolvedModel) {
85
+ + return $resolvedModel;
86
+ + }
87
+ +
88
+ + $model = (new $class)->newQueryForRestoration($key)->useWritePdo()->firstOrFail();
89
+ +
90
+ + SupportModels::rememberResolvedModel($model);
91
+ +
92
+ + return $model;
93
+ });
94
+ }
95
+
96
+ diff --git a/src/Features/SupportModels/SupportModels.php b/src/Features/SupportModels/SupportModels.php
97
+ index 7a8b1691..afc9e89c 100644
98
+ --- a/src/Features/SupportModels/SupportModels.php
99
+ +++ b/src/Features/SupportModels/SupportModels.php
100
+ @@ -2,15 +2,62 @@
101
+
102
+ namespace Livewire\Features\SupportModels;
103
+
104
+ +use function Livewire\on;
105
+ +use Livewire\Mechanisms\PersistentMiddleware\PersistentMiddleware;
106
+ use Livewire\ComponentHook;
107
+
108
+ class SupportModels extends ComponentHook
109
+ {
110
+ + public static $resolvedModels = [];
111
+ +
112
+ + public static $staleModels = [];
113
+ +
114
+ static function provide()
115
+ {
116
+ app('livewire')->propertySynthesizer([
117
+ ModelSynth::class,
118
+ EloquentCollectionSynth::class,
119
+ ]);
120
+ +
121
+ + on('flush-state', function () {
122
+ + static::$resolvedModels = [];
123
+ + static::$staleModels = [];
124
+ + });
125
+ + }
126
+ +
127
+ + static function rememberResolvedModel($model)
128
+ + {
129
+ + $hash = get_class($model).':'.$model->getKey();
130
+ +
131
+ + // Don't track models that have gone stale, otherwise a deletion or an
132
+ + // update made through the original instance couldn't be detected...
133
+ + if (isset(static::$staleModels[$hash])) return;
134
+ +
135
+ + static::$resolvedModels[$hash] = $model;
136
+ + }
137
+ +
138
+ + static function getResolvedModel($class, $key)
139
+ + {
140
+ + $hash = $class.':'.$key;
141
+ +
142
+ + if (isset(static::$staleModels[$hash])) return null;
143
+ +
144
+ + $model = static::$resolvedModels[$hash]
145
+ + ?? app(PersistentMiddleware::class)->getResolvedRouteModel($class, $key);
146
+ +
147
+ + if (! $model) return null;
148
+ +
149
+ + // Only reuse an instance that is indistinguishable from a freshly queried
150
+ + // one. Once an instance has been deleted or mutated, stop sharing that
151
+ + // model for the rest of the request and fall back to fresh queries...
152
+ + if (! $model->exists || $model->isDirty() || $model->wasChanged()) {
153
+ + static::$staleModels[$hash] = true;
154
+ +
155
+ + unset(static::$resolvedModels[$hash]);
156
+ +
157
+ + return null;
158
+ + }
159
+ +
160
+ + return $model;
161
+ }
162
+ }
163
+ diff --git a/src/Features/SupportModels/UnitTest.php b/src/Features/SupportModels/UnitTest.php
164
+ index 76a9072c..e025938b 100644
165
+ --- a/src/Features/SupportModels/UnitTest.php
166
+ +++ b/src/Features/SupportModels/UnitTest.php
167
+ @@ -325,6 +325,406 @@ class UnitTest extends \Tests\TestCase
168
+ $this->assertCount(1, array_values($articleQueries));
169
+ }
170
+
171
+ + public function test_a_model_property_reuses_a_model_already_hydrated_by_a_collection_property()
172
+ + {
173
+ + $component = Livewire::test(new class extends \Livewire\Component {
174
+ + public Collection $articles;
175
+ +
176
+ + public Article $selected;
177
+ +
178
+ + public function mount() {
179
+ + $this->articles = Article::all();
180
+ + $this->selected = $this->articles->first();
181
+ + }
182
+ +
183
+ + public function render() { return <<<'HTML'
184
+ + <div>
185
+ + @foreach($articles as $article)
186
+ + {{ $article->title.'-'.$loop->index }}
187
+ + @endforeach
188
+ + {{ 'Selected: '.$selected->title }}
189
+ + </div>
190
+ + HTML; }
191
+ + });
192
+ +
193
+ + Article::resolveConnection()->enableQueryLog();
194
+ + Article::resolveConnection()->flushQueryLog();
195
+ +
196
+ + $component->call('$refresh')
197
+ + ->assertSee('First-0')
198
+ + ->assertSee('Second-1')
199
+ + ->assertSee('Selected: First');
200
+ +
201
+ + $this->assertCount(1, Article::resolveConnection()->getQueryLog());
202
+ + }
203
+ +
204
+ + public function test_a_collection_property_only_queries_models_not_already_hydrated_by_a_model_property()
205
+ + {
206
+ + $component = Livewire::test(new class extends \Livewire\Component {
207
+ + public Article $selected;
208
+ +
209
+ + public Collection $articles;
210
+ +
211
+ + public function mount() {
212
+ + $this->selected = Article::first();
213
+ + $this->articles = Article::all();
214
+ + }
215
+ +
216
+ + public function render() { return <<<'HTML'
217
+ + <div>
218
+ + {{ 'Selected: '.$selected->title }}
219
+ + @foreach($articles as $article)
220
+ + {{ $article->title.'-'.$loop->index }}
221
+ + @endforeach
222
+ + </div>
223
+ + HTML; }
224
+ + });
225
+ +
226
+ + Article::resolveConnection()->enableQueryLog();
227
+ + Article::resolveConnection()->flushQueryLog();
228
+ +
229
+ + $component->call('$refresh')
230
+ + ->assertSee('Selected: First')
231
+ + ->assertSee('First-0')
232
+ + ->assertSee('Second-1');
233
+ +
234
+ + $queryLog = Article::resolveConnection()->getQueryLog();
235
+ +
236
+ + $this->assertCount(2, $queryLog);
237
+ +
238
+ + // The collection query should only restore the model that wasn't already
239
+ + // resolved by the model property. Integer keys may be inlined into the
240
+ + // SQL or passed as bindings depending on the Laravel version...
241
+ + [$modelQuery, $collectionQuery] = $queryLog;
242
+ +
243
+ + $this->assertTrue(
244
+ + str_contains($collectionQuery['query'], 'in (2)') || $collectionQuery['bindings'] === [2],
245
+ + 'The collection should only have queried for the unresolved model',
246
+ + );
247
+ + }
248
+ +
249
+ + public function test_two_model_properties_with_the_same_key_are_hydrated_with_one_query()
250
+ + {
251
+ + $component = Livewire::test(new class extends \Livewire\Component {
252
+ + public Article $first;
253
+ +
254
+ + public Article $second;
255
+ +
256
+ + public function mount() {
257
+ + $this->first = Article::first();
258
+ + $this->second = Article::first();
259
+ + }
260
+ +
261
+ + public function render() { return <<<'HTML'
262
+ + <div>{{ 'a:'.$first->title }} {{ 'b:'.$second->title }}</div>
263
+ + HTML; }
264
+ + });
265
+ +
266
+ + Article::resolveConnection()->enableQueryLog();
267
+ + Article::resolveConnection()->flushQueryLog();
268
+ +
269
+ + $component->call('$refresh')
270
+ + ->assertSee('a:First')
271
+ + ->assertSee('b:First');
272
+ +
273
+ + $this->assertCount(1, Article::resolveConnection()->getQueryLog());
274
+ + }
275
+ +
276
+ + public function test_reused_model_instances_are_shared_within_a_request()
277
+ + {
278
+ + Livewire::test(new class extends \Livewire\Component {
279
+ + public Collection $articles;
280
+ +
281
+ + public Article $selected;
282
+ +
283
+ + public function mount() {
284
+ + $this->articles = Article::all();
285
+ + $this->selected = $this->articles->first();
286
+ + }
287
+ +
288
+ + public function rename() {
289
+ + $this->articles->count();
290
+ +
291
+ + $this->selected->title = 'Renamed';
292
+ + }
293
+ +
294
+ + public function render() { return <<<'HTML'
295
+ + <div>
296
+ + @foreach($articles as $article)
297
+ + {{ $article->title.'-'.$loop->index }}
298
+ + @endforeach
299
+ + </div>
300
+ + HTML; }
301
+ + })
302
+ + ->call('rename')
303
+ + ->assertSee('Renamed-0')
304
+ + ->assertSee('Second-1');
305
+ + }
306
+ +
307
+ + public function test_a_collection_is_not_queried_when_all_its_models_are_already_resolved()
308
+ + {
309
+ + $component = Livewire::test(new class extends \Livewire\Component {
310
+ + public Article $one;
311
+ +
312
+ + public Article $two;
313
+ +
314
+ + public Collection $articles;
315
+ +
316
+ + public function mount() {
317
+ + $this->one = Article::find(1);
318
+ + $this->two = Article::find(2);
319
+ + $this->articles = new Collection([Article::find(1), Article::find(1), Article::find(2)]);
320
+ + }
321
+ +
322
+ + public function render() { return <<<'HTML'
323
+ + <div>
324
+ + {{ 'a:'.$one->title }} {{ 'b:'.$two->title }}
325
+ + @foreach($articles as $article)
326
+ + {{ $article->title.'-'.$loop->index }}
327
+ + @endforeach
328
+ + </div>
329
+ + HTML; }
330
+ + });
331
+ +
332
+ + Article::resolveConnection()->enableQueryLog();
333
+ + Article::resolveConnection()->flushQueryLog();
334
+ +
335
+ + $component->call('$refresh')
336
+ + ->assertSee('a:First')
337
+ + ->assertSee('b:Second')
338
+ + ->assertSee('First-0')
339
+ + ->assertSee('First-1')
340
+ + ->assertSee('Second-2');
341
+ +
342
+ + $this->assertCount(2, Article::resolveConnection()->getQueryLog());
343
+ + }
344
+ +
345
+ + public function test_resolved_models_are_not_reused_across_requests()
346
+ + {
347
+ + $component = Livewire::test(new class extends \Livewire\Component {
348
+ + public Article $article;
349
+ +
350
+ + public function mount() {
351
+ + $this->article = Article::first();
352
+ + }
353
+ +
354
+ + public function render() { return <<<'HTML'
355
+ + <div>{{ $article->title }}</div>
356
+ + HTML; }
357
+ + });
358
+ +
359
+ + Article::resolveConnection()->enableQueryLog();
360
+ + Article::resolveConnection()->flushQueryLog();
361
+ +
362
+ + $component->call('$refresh')->assertSee('First');
363
+ + $component->call('$refresh')->assertSee('First');
364
+ +
365
+ + $this->assertCount(2, Article::resolveConnection()->getQueryLog());
366
+ + }
367
+ +
368
+ + public function test_a_mutated_model_is_not_reused_by_other_properties()
369
+ + {
370
+ + // On earlier versions there are no lazy proxies, so properties hydrate
371
+ + // eagerly before any mutations and share the still-clean instance...
372
+ + if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies');
373
+ +
374
+ + $component = Livewire::test(new class extends \Livewire\Component {
375
+ + public Article $first;
376
+ +
377
+ + public Article $second;
378
+ +
379
+ + public function mount() {
380
+ + $this->first = Article::first();
381
+ + $this->second = Article::first();
382
+ + }
383
+ +
384
+ + public function rename() {
385
+ + $this->first->title = 'Draft';
386
+ + }
387
+ +
388
+ + public function render() { return <<<'HTML'
389
+ + <div>{{ 'a:'.$first->title }} {{ 'b:'.$second->title }}</div>
390
+ + HTML; }
391
+ + });
392
+ +
393
+ + Article::resolveConnection()->enableQueryLog();
394
+ + Article::resolveConnection()->flushQueryLog();
395
+ +
396
+ + // The unsaved mutation on $first shouldn't leak into $second — it
397
+ + // should fall through to a fresh query instead...
398
+ + $component->call('rename')
399
+ + ->assertSee('a:Draft')
400
+ + ->assertSee('b:First');
401
+ +
402
+ + $this->assertCount(2, Article::resolveConnection()->getQueryLog());
403
+ + }
404
+ +
405
+ + public function test_a_deleted_model_is_not_reused_when_hydrating_a_collection()
406
+ + {
407
+ + // On earlier versions there are no lazy proxies, so the collection is
408
+ + // hydrated eagerly before the deletion, like it is on main...
409
+ + if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies');
410
+ +
411
+ + $this->resetMutableArticles();
412
+ +
413
+ + Livewire::test(new class extends \Livewire\Component {
414
+ + public Collection $articles;
415
+ +
416
+ + public MutableArticle $selected;
417
+ +
418
+ + public function mount() {
419
+ + $this->articles = MutableArticle::all();
420
+ + $this->selected = $this->articles->first();
421
+ + }
422
+ +
423
+ + public function deleteSelected() {
424
+ + $this->selected->delete();
425
+ + }
426
+ +
427
+ + public function render() { return <<<'HTML'
428
+ + <div>
429
+ + @foreach($articles as $article)
430
+ + {{ $article->title.'-'.$loop->index }}
431
+ + @endforeach
432
+ + </div>
433
+ + HTML; }
434
+ + })
435
+ + ->call('deleteSelected')
436
+ + ->assertDontSee('First-')
437
+ + ->assertSee('Second-0');
438
+ + }
439
+ +
440
+ + public function test_a_saved_model_is_not_reused_by_other_properties()
441
+ + {
442
+ + if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies');
443
+ +
444
+ + $this->resetMutableArticles();
445
+ +
446
+ + $component = Livewire::test(new class extends \Livewire\Component {
447
+ + public MutableArticle $first;
448
+ +
449
+ + public MutableArticle $second;
450
+ +
451
+ + public function mount() {
452
+ + $this->first = MutableArticle::find(1);
453
+ + $this->second = MutableArticle::find(1);
454
+ + }
455
+ +
456
+ + public function rename() {
457
+ + $this->first->update(['title' => 'Renamed']);
458
+ + }
459
+ +
460
+ + public function render() { return <<<'HTML'
461
+ + <div>{{ 'a:'.$first->title }} {{ 'b:'.$second->title }}</div>
462
+ + HTML; }
463
+ + });
464
+ +
465
+ + MutableArticle::resolveConnection()->enableQueryLog();
466
+ + MutableArticle::resolveConnection()->flushQueryLog();
467
+ +
468
+ + // The saved model shouldn't be reused for $second — it should fall
469
+ + // through to a fresh query, which reads the same saved title...
470
+ + $component->call('rename')
471
+ + ->assertSee('a:Renamed')
472
+ + ->assertSee('b:Renamed');
473
+ +
474
+ + $selects = array_filter(
475
+ + MutableArticle::resolveConnection()->getQueryLog(),
476
+ + fn ($q) => str_starts_with($q['query'], 'select'),
477
+ + );
478
+ +
479
+ + $this->assertCount(2, $selects);
480
+ + }
481
+ +
482
+ + public function test_a_model_saved_after_its_reuse_was_rejected_is_not_served_stale()
483
+ + {
484
+ + if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies');
485
+ +
486
+ + $this->resetMutableArticles();
487
+ +
488
+ + Livewire::test(new class extends \Livewire\Component {
489
+ + public MutableArticle $first;
490
+ +
491
+ + public MutableArticle $second;
492
+ +
493
+ + public Collection $articles;
494
+ +
495
+ + public function mount() {
496
+ + $this->first = MutableArticle::find(1);
497
+ + $this->second = MutableArticle::find(1);
498
+ + $this->articles = MutableArticle::all();
499
+ + }
500
+ +
501
+ + public function rename() {
502
+ + // Once a mutated instance is encountered, the model shouldn't be
503
+ + // shared for the rest of the request — even after the collection
504
+ + // resolves a clean instance while the mutation is unsaved...
505
+ + $this->first->title = 'Renamed';
506
+ +
507
+ + $this->articles->count();
508
+ +
509
+ + $this->first->save();
510
+ + }
511
+ +
512
+ + public function render() { return <<<'HTML'
513
+ + <div>{{ 'b:'.$second->title }}</div>
514
+ + HTML; }
515
+ + })
516
+ + ->call('rename')
517
+ + ->assertSee('b:Renamed');
518
+ + }
519
+ +
520
+ + public function test_a_model_deleted_after_its_reuse_was_rejected_is_not_resurrected()
521
+ + {
522
+ + if (PHP_VERSION_ID < 80400) $this->markTestSkipped('Requires lazy model proxies');
523
+ +
524
+ + $this->resetMutableArticles();
525
+ +
526
+ + Livewire::test(new class extends \Livewire\Component {
527
+ + public MutableArticle $selected;
528
+ +
529
+ + public Collection $articles;
530
+ +
531
+ + public Collection $others;
532
+ +
533
+ + public function mount() {
534
+ + $this->selected = MutableArticle::find(1);
535
+ + $this->articles = MutableArticle::all();
536
+ + $this->others = MutableArticle::all();
537
+ + }
538
+ +
539
+ + public function deleteSelected() {
540
+ + $this->selected->title = 'Doomed';
541
+ +
542
+ + $this->articles->count();
543
+ +
544
+ + $this->selected->delete();
545
+ + }
546
+ +
547
+ + public function render() { return <<<'HTML'
548
+ + <div>
549
+ + @foreach($others as $article)
550
+ + {{ $article->title.'-'.$loop->index }}
551
+ + @endforeach
552
+ + </div>
553
+ + HTML; }
554
+ + })
555
+ + ->call('deleteSelected')
556
+ + ->assertDontSee('First-')
557
+ + ->assertDontSee('Doomed-')
558
+ + ->assertSee('Second-0');
559
+ + }
560
+ +
561
+ + protected function resetMutableArticles()
562
+ + {
563
+ + // Reset the table as these tests modify or delete its rows...
564
+ + MutableArticle::query()->delete();
565
+ + MutableArticle::insert([
566
+ + ['id' => 1, 'title' => 'First'],
567
+ + ['id' => 2, 'title' => 'Second'],
568
+ + ]);
569
+ + }
570
+ +
571
+ public function test_hydrating_an_empty_eloquent_collection_does_not_trigger_deprecations()
572
+ {
573
+ $component = Livewire::test(new class extends \Livewire\Component {
574
+ @@ -384,6 +784,19 @@ class Article extends Model
575
+ ];
576
+ }
577
+
578
+ +// Uses its own table so modifying or deleting rows doesn't affect other tests...
579
+ +class MutableArticle extends Model
580
+ +{
581
+ + use Sushi;
582
+ +
583
+ + protected $guarded = [];
584
+ +
585
+ + protected $rows = [
586
+ + ['title' => 'First'],
587
+ + ['title' => 'Second'],
588
+ + ];
589
+ +}
590
+ +
591
+ // Simulates tightenco/parental's HasParent trait, which overrides
592
+ // getTable() and getMorphClass() to return the parent's values so
593
+ // that polymorphic relations use the parent's table.